Merge pull request #8594 from JMAConsulting/CRM-18977
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 */
33 class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
34
35 /**
36 * Static field for all the contribution information that we can potentially import
37 *
38 * @var array
39 */
40 static $_importableFields = NULL;
41
42 /**
43 * Static field for all the contribution information that we can potentially export
44 *
45 * @var array
46 */
47 static $_exportableFields = NULL;
48
49 /**
50 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
52 */
53 public $_relatedObjects = array();
54
55 /**
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
60 *
61 * @var string component or event
62 */
63 public $_component = NULL;
64
65 /**
66 * Possibly obsolete variable.
67 *
68 * If you use it please explain why it is set in the create function here.
69 *
70 * @var string
71 */
72 public $trxn_result_code;
73
74 /**
75 * Class constructor.
76 */
77 public function __construct() {
78 parent::__construct();
79 }
80
81 /**
82 * Takes an associative array and creates a contribution object.
83 *
84 * the function extract all the params it needs to initialize the create a
85 * contribution object. the params array could contain additional unused name/value
86 * pairs
87 *
88 * @param array $params
89 * (reference ) an assoc array of name/value pairs.
90 * @param array $ids
91 * The array that holds all the db ids.
92 *
93 * @return CRM_Contribute_BAO_Contribution|void
94 */
95 public static function add(&$params, $ids = array()) {
96 if (empty($params)) {
97 return NULL;
98 }
99 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
100 $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params));
101 $duplicates = array();
102 if (self::checkDuplicate($params, $duplicates, $contributionID)) {
103 $error = CRM_Core_Error::singleton();
104 $d = implode(', ', $duplicates);
105 $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
106 'Fatal',
107 array($d),
108 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
109 );
110 return $error;
111 }
112
113 // first clean up all the money fields
114 $moneyFields = array(
115 'total_amount',
116 'net_amount',
117 'fee_amount',
118 'non_deductible_amount',
119 );
120
121 //if priceset is used, no need to cleanup money
122 if (!empty($params['skipCleanMoney'])) {
123 unset($moneyFields[0]);
124 }
125
126 foreach ($moneyFields as $field) {
127 if (isset($params[$field])) {
128 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
129 }
130 }
131
132 //set defaults in create mode
133 if (!$contributionID) {
134 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
135 }
136
137 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
138 //if contribution is created with cancelled or refunded status, add credit note id
139 if (!empty($params['contribution_status_id'])) {
140 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
141 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
142 || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
143 ) {
144 if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") {
145 $params['creditnote_id'] = self::createCreditNoteId();
146 }
147 }
148 }
149 else {
150 // Since the fee amount is expecting this (later on) ensure it is always set.
151 // It would only not be set for an update where it is unchanged.
152 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
153 }
154
155 if (!$contributionID
156 && CRM_Utils_Array::value('membership_id', $params)
157 && self::checkContributeSettings('deferred_revenue_enabled')
158 ) {
159 $memberStartDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
160 if ($memberStartDate) {
161 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
162 }
163 }
164 self::calculateMissingAmountParams($params, $contributionID);
165
166 if (!empty($params['payment_instrument_id'])) {
167 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
168 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
169 $params['check_number'] = 'null';
170 }
171 }
172
173 $setPrevContribution = TRUE;
174 // CRM-13964 partial payment
175 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
176 $partialAmtTotal = $params['partial_payment_total'];
177 $partialAmtPay = $params['partial_amount_pay'];
178 $params['total_amount'] = $partialAmtTotal;
179 if ($partialAmtPay < $partialAmtTotal) {
180 $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name');
181 $params['is_pay_later'] = 0;
182 $setPrevContribution = FALSE;
183 }
184 }
185 if ($contributionID && $setPrevContribution) {
186 $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
187 }
188
189 if ($contributionID) {
190 CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params);
191 }
192 else {
193 CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params);
194 }
195 $contribution = new CRM_Contribute_BAO_Contribution();
196 $contribution->copyValues($params);
197
198 $contribution->id = $contributionID;
199
200 if (empty($contribution->id)) {
201 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
202 if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
203 $contribution->currency = CRM_Core_Config::singleton()->defaultCurrency;
204 }
205 }
206
207 $result = $contribution->save();
208
209 // Add financial_trxn details as part of fix for CRM-4724
210 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
211 $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
212
213 //add Account details
214 $params['contribution'] = $contribution;
215 self::recordFinancialAccounts($params);
216
217 if (self::isUpdateToRecurringContribution($params)) {
218 CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment(
219 (!empty($params['contribution_recur_id']) ? $params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id),
220 $contributionStatus[$params['contribution_status_id']]
221 );
222 }
223
224 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
225
226 if ($contributionID) {
227 CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
228 }
229 else {
230 CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
231 }
232
233 return $result;
234 }
235
236 /**
237 * Is this contribution updating an existing recurring contribution.
238 *
239 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
240 * pending payment is being confirmed (or failing).
241 *
242 * @param array $params
243 *
244 * @return bool
245 */
246 public static function isUpdateToRecurringContribution($params) {
247 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
248 return TRUE;
249 }
250 if (empty($params['prevContribution']) || empty($params['contribution_status_id'])) {
251 return FALSE;
252 }
253 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id)) {
254 return FALSE;
255 }
256 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
257 if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) {
258 return TRUE;
259 }
260 return FALSE;
261 }
262
263 /**
264 * Get defaults for new entity.
265 * @return array
266 */
267 public static function getDefaults() {
268 return array(
269 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument',
270 FALSE, FALSE, FALSE, 'AND is_default = 1')
271 ),
272 'contribution_status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'),
273 );
274 }
275
276 /**
277 * Fetch the object and store the values in the values array.
278 *
279 * @param array $params
280 * Input parameters to find object.
281 * @param array $values
282 * Output values of the object.
283 * @param array $ids
284 * The array that holds all the db ids.
285 *
286 * @return CRM_Contribute_BAO_Contribution|null
287 * The found object or null
288 */
289 public static function getValues($params, &$values, &$ids) {
290 if (empty($params)) {
291 return NULL;
292 }
293 $contribution = new CRM_Contribute_BAO_Contribution();
294
295 $contribution->copyValues($params);
296
297 if ($contribution->find(TRUE)) {
298 $ids['contribution'] = $contribution->id;
299
300 CRM_Core_DAO::storeValues($contribution, $values);
301
302 return $contribution;
303 }
304 $null = NULL; // return by reference
305 return $null;
306 }
307
308 /**
309 * Get the values and resolve the most common mappings.
310 *
311 * Since contribution status is resolved in almost every function that calls getValues it makes
312 * sense to have an extra function to resolve it rather than repeat the code.
313 *
314 * Think carefully before adding more mappings to be resolved as there could be performance implications
315 * if this function starts to be called from more iterative functions.
316 *
317 * @param array $params
318 * Input parameters to find object.
319 *
320 * @return array
321 * Array of the found contribution.
322 * @throws CRM_Core_Exception
323 */
324 public static function getValuesWithMappings($params) {
325 $values = $ids = array();
326 $contribution = self::getValues($params, $values, $ids);
327 if (is_null($contribution)) {
328 throw new CRM_Core_Exception('No contribution found');
329 }
330 $values['contribution_status'] = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
331 return $values;
332 }
333
334 /**
335 * Calculate net_amount & fee_amount if they are not set.
336 *
337 * Net amount should be total - fee.
338 * This should only be called for new contributions.
339 *
340 * @param array $params
341 * Params for a new contribution before they are saved.
342 * @param int|null $contributionID
343 * Contribution ID if we are dealing with an update.
344 *
345 * @throws \CiviCRM_API3_Exception
346 */
347 public static function calculateMissingAmountParams(&$params, $contributionID) {
348 if (!$contributionID && !isset($params['fee_amount'])) {
349 if (isset($params['total_amount']) && isset($params['net_amount'])) {
350 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
351 }
352 else {
353 $params['fee_amount'] = 0;
354 }
355 }
356 if (!isset($params['net_amount'])) {
357 if (!$contributionID) {
358 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
359 }
360 else {
361 if (isset($params['fee_amount']) || isset($params['total_amount'])) {
362 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
363 // net_amount may need adjusting.
364 $contribution = civicrm_api3('Contribution', 'getsingle', array(
365 'id' => $contributionID,
366 'return' => array('total_amount', 'net_amount'),
367 ));
368 $totalAmount = isset($params['total_amount']) ? $params['total_amount'] : CRM_Utils_Array::value('total_amount', $contribution);
369 $feeAmount = isset($params['fee_amount']) ? $params['fee_amount'] : CRM_Utils_Array::value('fee_amount', $contribution);
370 $params['net_amount'] = $totalAmount - $feeAmount;
371 }
372 }
373 }
374 }
375
376 /**
377 * @param $params
378 * @param $billingLocationTypeID
379 *
380 * @return array
381 */
382 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
383 $hasBillingField = FALSE;
384 $billingFields = array(
385 'street_address',
386 'city',
387 'state_province_id',
388 'postal_code',
389 'country_id',
390 );
391
392 //build address array
393 $addressParams = array();
394 $addressParams['location_type_id'] = $billingLocationTypeID;
395 $addressParams['is_billing'] = 1;
396
397 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
398 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
399 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
400 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
401
402 foreach ($billingFields as $value) {
403 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
404 if (!empty($addressParams[$value])) {
405 $hasBillingField = TRUE;
406 }
407 }
408 return array($hasBillingField, $addressParams);
409 }
410
411 /**
412 * Get address params ready to be passed to the payment processor.
413 *
414 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
415 * To create an address we need state_province_id.
416 *
417 * @param array $params
418 * @param int $billingLocationTypeID
419 *
420 * @return array
421 */
422 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
423 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
424 foreach ($addressParams as $name => $field) {
425 if (substr($name, 0, 8) == 'billing_') {
426 $addressParams[substr($name, 9)] = $addressParams[$field];
427 }
428 }
429 return array($hasBillingField, $addressParams);
430 }
431
432 /**
433 * Get the number of terms for this contribution for a given membership type
434 * based on querying the line item table and relevant price field values
435 * Note that any one contribution should only be able to have one line item relating to a particular membership
436 * type
437 *
438 * @param int $membershipTypeID
439 *
440 * @param int $contributionID
441 *
442 * @return int
443 */
444 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
445 $numTerms = CRM_Core_DAO::singleValueQuery("
446 SELECT membership_num_terms FROM civicrm_line_item li
447 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
448 WHERE contribution_id = %1 AND membership_type_id = %2",
449 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
450 );
451 // default of 1 is precautionary
452 return empty($numTerms) ? 1 : $numTerms;
453 }
454
455 /**
456 * Takes an associative array and creates a contribution object.
457 *
458 * @param array $params
459 * (reference ) an assoc array of name/value pairs.
460 * @param array $ids
461 * The array that holds all the db ids.
462 *
463 * @return CRM_Contribute_BAO_Contribution
464 */
465 public static function create(&$params, $ids = array()) {
466 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
467 foreach ($dateFields as $df) {
468 if (isset($params[$df])) {
469 $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
470 }
471 }
472
473 //if contribution is created with cancelled or refunded status, add credit note id
474 if (!empty($params['contribution_status_id'])) {
475 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
476
477 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
478 || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
479 ) {
480 if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") {
481 $params['creditnote_id'] = self::createCreditNoteId();
482 }
483 }
484 }
485
486 $transaction = new CRM_Core_Transaction();
487
488 $contribution = self::add($params, $ids);
489
490 if (is_a($contribution, 'CRM_Core_Error')) {
491 $transaction->rollback();
492 return $contribution;
493 }
494
495 $params['contribution_id'] = $contribution->id;
496
497 if (!empty($params['custom']) &&
498 is_array($params['custom'])
499 ) {
500 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
501 }
502
503 $session = CRM_Core_Session::singleton();
504
505 if (!empty($params['note'])) {
506 $noteParams = array(
507 'entity_table' => 'civicrm_contribution',
508 'note' => $params['note'],
509 'entity_id' => $contribution->id,
510 'contact_id' => $session->get('userID'),
511 'modified_date' => date('Ymd'),
512 );
513 if (!$noteParams['contact_id']) {
514 $noteParams['contact_id'] = $params['contact_id'];
515 }
516 CRM_Core_BAO_Note::add($noteParams);
517 }
518
519 // make entry in batch entity batch table
520 if (!empty($params['batch_id'])) {
521 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
522 $titleFields = array(
523 'contact_id',
524 'total_amount',
525 'currency',
526 'financial_type_id',
527 );
528 $retrieveRequired = 0;
529 foreach ($titleFields as $titleField) {
530 if (!isset($contribution->$titleField)) {
531 $retrieveRequired = 1;
532 break;
533 }
534 }
535 if ($retrieveRequired == 1) {
536 $contribution->find(TRUE);
537 }
538 }
539
540 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
541
542 $transaction->commit();
543
544 // check if activity record exist for this contribution, if
545 // not add activity
546 $activity = new CRM_Activity_DAO_Activity();
547 $activity->source_record_id = $contribution->id;
548 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
549 'Contribution',
550 'name'
551 );
552
553 //CRM-18406: Update activity when edit contribution.
554 if ($activity->find(TRUE)) {
555 // CRM-13237 : if activity record found, update it with campaign id of contribution
556 CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
557 $contribution->activity_id = $activity->id;
558 }
559 if (empty($contribution->contact_id)) {
560 $contribution->find(TRUE);
561 }
562 CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
563
564 // do not add to recent items for import, CRM-4399
565 if (empty($params['skipRecentView'])) {
566 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
567 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
568 );
569 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
570 $titleFields = array(
571 'contact_id',
572 'total_amount',
573 'currency',
574 'financial_type_id',
575 );
576 $retrieveRequired = 0;
577 foreach ($titleFields as $titleField) {
578 if (!isset($contribution->$titleField)) {
579 $retrieveRequired = 1;
580 break;
581 }
582 }
583 if ($retrieveRequired == 1) {
584 $contribution->find(TRUE);
585 }
586 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
587 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
588
589 $recentOther = array();
590 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
591 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
592 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
593 );
594 }
595
596 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
597 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
598 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
599 );
600 }
601
602 // add the recently created Contribution
603 CRM_Utils_Recent::add($title,
604 $url,
605 $contribution->id,
606 'Contribution',
607 $contribution->contact_id,
608 NULL,
609 $recentOther
610 );
611 }
612
613 return $contribution;
614 }
615
616 /**
617 * Get the values for pseudoconstants for name->value and reverse.
618 *
619 * @param array $defaults
620 * (reference) the default values, some of which need to be resolved.
621 * @param bool $reverse
622 * True if we want to resolve the values in the reverse direction (value -> name).
623 */
624 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
625 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
626 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
627 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse);
628 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
629 }
630
631 /**
632 * Convert associative array names to values and vice-versa.
633 *
634 * This function is used by both the web form layer and the api. Note that
635 * the api needs the name => value conversion, also the view layer typically
636 * requires value => name conversion
637 *
638 * @param array $defaults
639 * @param string $property
640 * @param array $lookup
641 * @param bool $reverse
642 *
643 * @return bool
644 */
645 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
646 $id = $property . '_id';
647
648 $src = $reverse ? $property : $id;
649 $dst = $reverse ? $id : $property;
650
651 if (!array_key_exists($src, $defaults)) {
652 return FALSE;
653 }
654
655 $look = $reverse ? array_flip($lookup) : $lookup;
656
657 if (is_array($look)) {
658 if (!array_key_exists($defaults[$src], $look)) {
659 return FALSE;
660 }
661 }
662 $defaults[$dst] = $look[$defaults[$src]];
663 return TRUE;
664 }
665
666 /**
667 * Retrieve DB object based on input parameters.
668 *
669 * It also stores all the retrieved values in the default array.
670 *
671 * @param array $params
672 * (reference ) an assoc array of name/value pairs.
673 * @param array $defaults
674 * (reference ) an assoc array to hold the name / value pairs.
675 * in a hierarchical manner
676 * @param array $ids
677 * (reference) the array that holds all the db ids.
678 *
679 * @return CRM_Contribute_BAO_Contribution
680 */
681 public static function retrieve(&$params, &$defaults, &$ids) {
682 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
683 return $contribution;
684 }
685
686 /**
687 * Combine all the importable fields from the lower levels object.
688 *
689 * The ordering is important, since currently we do not have a weight
690 * scheme. Adding weight is super important and should be done in the
691 * next week or so, before this can be called complete.
692 *
693 * @param string $contactType
694 * @param bool $status
695 *
696 * @return array
697 * array of importable Fields
698 */
699 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
700 if (!self::$_importableFields) {
701 if (!self::$_importableFields) {
702 self::$_importableFields = array();
703 }
704
705 if (!$status) {
706 $fields = array('' => array('title' => ts('- do not import -')));
707 }
708 else {
709 $fields = array('' => array('title' => ts('- Contribution Fields -')));
710 }
711
712 $note = CRM_Core_DAO_Note::import();
713 $tmpFields = CRM_Contribute_DAO_Contribution::import();
714 unset($tmpFields['option_value']);
715 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
716 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
717
718 // Using new Dedupe rule.
719 $ruleParams = array(
720 'contact_type' => $contactType,
721 'used' => 'Unsupervised',
722 );
723 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
724 $tmpContactField = array();
725 if (is_array($fieldsArray)) {
726 foreach ($fieldsArray as $value) {
727 //skip if there is no dupe rule
728 if ($value == 'none') {
729 continue;
730 }
731 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
732 $value,
733 'id',
734 'column_name'
735 );
736 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
737 $tmpContactField[trim($value)] = $contactFields[trim($value)];
738 if (!$status) {
739 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
740 }
741 else {
742 $title = $tmpContactField[trim($value)]['title'];
743 }
744 $tmpContactField[trim($value)]['title'] = $title;
745 }
746 }
747
748 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
749 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
750 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
751 $fields = array_merge($fields, $tmpContactField);
752 $fields = array_merge($fields, $tmpFields);
753 $fields = array_merge($fields, $note);
754 $fields = array_merge($fields, $optionFields);
755 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
756 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
757 self::$_importableFields = $fields;
758 }
759 return self::$_importableFields;
760 }
761
762 /**
763 * Combine all the exportable fields from the lower level objects.
764 *
765 * @param bool $checkPermission
766 *
767 * @return array
768 * array of exportable Fields
769 */
770 public static function &exportableFields($checkPermission = TRUE) {
771 if (!self::$_exportableFields) {
772 if (!self::$_exportableFields) {
773 self::$_exportableFields = array();
774 }
775
776 $impFields = CRM_Contribute_DAO_Contribution::export();
777 $expFieldProduct = CRM_Contribute_DAO_Product::export();
778 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export();
779 $typeField = CRM_Financial_DAO_FinancialType::export();
780 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
781 $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute');
782 $contributionStatus = array(
783 'contribution_status' => array(
784 'title' => ts('Contribution Status'),
785 'name' => 'contribution_status',
786 'data_type' => CRM_Utils_Type::T_STRING,
787 ),
788 );
789
790 $contributionPage = array(
791 'contribution_page' => array(
792 'title' => ts('Contribution Page'),
793 'name' => 'contribution_page',
794 'where' => 'civicrm_contribution_page.title',
795 'data_type' => CRM_Utils_Type::T_STRING,
796 ),
797 );
798
799 $contributionNote = array(
800 'contribution_note' => array(
801 'title' => ts('Contribution Note'),
802 'name' => 'contribution_note',
803 'data_type' => CRM_Utils_Type::T_TEXT,
804 ),
805 );
806
807 $contributionRecurId = array(
808 'contribution_recur_id' => array(
809 'title' => ts('Recurring Contributions ID'),
810 'name' => 'contribution_recur_id',
811 'where' => 'civicrm_contribution.contribution_recur_id',
812 'data_type' => CRM_Utils_Type::T_INT,
813 ),
814 );
815
816 $extraFields = array(
817 'contribution_batch' => array(
818 'title' => ts('Batch Name'),
819 ),
820 );
821
822 // CRM-17787
823 $campaignTitle = array(
824 'contribution_campaign_title' => array(
825 'title' => ts('Campaign Title'),
826 'name' => 'campaign_title',
827 'where' => 'civicrm_campaign.title',
828 'data_type' => CRM_Utils_Type::T_STRING,
829 ),
830 );
831 $softCreditFields = array(
832 'contribution_soft_credit_name' => array(
833 'name' => 'contribution_soft_credit_name',
834 'title' => 'Soft Credit For',
835 'where' => 'civicrm_contact_d.display_name',
836 'data_type' => CRM_Utils_Type::T_STRING,
837 ),
838 'contribution_soft_credit_amount' => array(
839 'name' => 'contribution_soft_credit_amount',
840 'title' => 'Soft Credit Amount',
841 'where' => 'civicrm_contribution_soft.amount',
842 'data_type' => CRM_Utils_Type::T_MONEY,
843 ),
844 'contribution_soft_credit_type' => array(
845 'name' => 'contribution_soft_credit_type',
846 'title' => 'Soft Credit Type',
847 'where' => 'contribution_softcredit_type.label',
848 'data_type' => CRM_Utils_Type::T_STRING,
849 ),
850 'contribution_soft_credit_contribution_id' => array(
851 'name' => 'contribution_soft_credit_contribution_id',
852 'title' => 'Soft Credit For Contribution ID',
853 'where' => 'civicrm_contribution_soft.contribution_id',
854 'data_type' => CRM_Utils_Type::T_INT,
855 ),
856 'contribution_soft_credit_contact_id' => array(
857 'name' => 'contribution_soft_credit_contact_id',
858 'title' => 'Soft Credit For Contact ID',
859 'where' => 'civicrm_contact_d.id',
860 'data_type' => CRM_Utils_Type::T_INT,
861 ),
862 );
863
864 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
865 $premiums = array(
866 'contribution_product_id' => array(
867 'title' => ts('Premium'),
868 'name' => 'contribution_product_id',
869 'where' => 'civicrm_product.id',
870 'data_type' => CRM_Utils_Type::T_INT,
871 ),
872 );
873
874 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
875 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
876 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
877 );
878
879 self::$_exportableFields = $fields;
880 }
881
882 return self::$_exportableFields;
883 }
884
885 /**
886 * @param null $status
887 * @param null $startDate
888 * @param null $endDate
889 *
890 * @return array|null
891 */
892 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
893 $where = array();
894 switch ($status) {
895 case 'Valid':
896 $where[] = 'contribution_status_id = 1';
897 break;
898
899 case 'Cancelled':
900 $where[] = 'contribution_status_id = 3';
901 break;
902 }
903
904 if ($startDate) {
905 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
906 }
907 if ($endDate) {
908 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
909 }
910 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
911 if ($financialTypes) {
912 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
913 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
914 }
915 else {
916 $where[] = "c.financial_type_id IN (0)";
917 }
918
919 $whereCond = implode(' AND ', $where);
920
921 $query = "
922 SELECT sum( total_amount ) as total_amount,
923 count( c.id ) as total_count,
924 currency
925 FROM civicrm_contribution c
926 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
927 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
928 WHERE $whereCond
929 AND ( is_test = 0 OR is_test IS NULL )
930 AND contact.is_deleted = 0
931 GROUP BY currency
932 ";
933
934 $dao = CRM_Core_DAO::executeQuery($query);
935 $amount = array();
936 $count = 0;
937 while ($dao->fetch()) {
938 $count += $dao->total_count;
939 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
940 }
941 if ($count) {
942 return array(
943 'amount' => implode(', ', $amount),
944 'count' => $count,
945 );
946 }
947 return NULL;
948 }
949
950 /**
951 * Delete the indirect records associated with this contribution first.
952 *
953 * @param int $id
954 *
955 * @return mixed|null
956 * $results no of deleted Contribution on success, false otherwise
957 */
958 public static function deleteContribution($id) {
959 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
960
961 $transaction = new CRM_Core_Transaction();
962
963 $results = NULL;
964 //delete activity record
965 $params = array(
966 'source_record_id' => $id,
967 // activity type id for contribution
968 'activity_type_id' => 6,
969 );
970
971 CRM_Activity_BAO_Activity::deleteActivity($params);
972
973 //delete billing address if exists for this contribution.
974 self::deleteAddress($id);
975
976 //update pledge and pledge payment, CRM-3961
977 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
978
979 // remove entry from civicrm_price_set_entity, CRM-5095
980 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
981 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
982 }
983 // cleanup line items.
984 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
985
986 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
987 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
988
989 if ($participantId) {
990 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
991 }
992 else {
993 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
994 }
995
996 //delete note.
997 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
998 $noteId = key($note);
999 if ($noteId) {
1000 CRM_Core_BAO_Note::del($noteId, FALSE);
1001 }
1002
1003 $dao = new CRM_Contribute_DAO_Contribution();
1004 $dao->id = $id;
1005
1006 $results = $dao->delete();
1007
1008 $transaction->commit();
1009
1010 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
1011
1012 // delete the recently created Contribution
1013 $contributionRecent = array(
1014 'id' => $id,
1015 'type' => 'Contribution',
1016 );
1017 CRM_Utils_Recent::del($contributionRecent);
1018
1019 return $results;
1020 }
1021
1022 /**
1023 * React to a financial transaction (payment) failure.
1024 *
1025 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1026 * payments is important for forensic and outreach reasons.
1027 *
1028 * @param int $contributionID
1029 * @param int $contactID
1030 * @param string $message
1031 *
1032 * @throws \CiviCRM_API3_Exception
1033 */
1034 public static function failPayment($contributionID, $contactID, $message) {
1035 civicrm_api3('activity', 'create', array(
1036 'activity_type_id' => 'Failed Payment',
1037 'details' => $message,
1038 'subject' => ts('Payment failed at payment processor'),
1039 'source_record_id' => $contributionID,
1040 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1041 $contactID,
1042 ));
1043 }
1044
1045 /**
1046 * Check if there is a contribution with the same trxn_id or invoice_id.
1047 *
1048 * @param array $input
1049 * An assoc array of name/value pairs.
1050 * @param array $duplicates
1051 * (reference) store ids of duplicate contribs.
1052 * @param int $id
1053 *
1054 * @return bool
1055 * true if duplicate, false otherwise
1056 */
1057 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1058 if (!$id) {
1059 $id = CRM_Utils_Array::value('id', $input);
1060 }
1061 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
1062 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
1063
1064 $clause = array();
1065 $input = array();
1066
1067 if ($trxn_id) {
1068 $clause[] = "trxn_id = %1";
1069 $input[1] = array($trxn_id, 'String');
1070 }
1071
1072 if ($invoice_id) {
1073 $clause[] = "invoice_id = %2";
1074 $input[2] = array($invoice_id, 'String');
1075 }
1076
1077 if (empty($clause)) {
1078 return FALSE;
1079 }
1080
1081 $clause = implode(' OR ', $clause);
1082 if ($id) {
1083 $clause = "( $clause ) AND id != %3";
1084 $input[3] = array($id, 'Integer');
1085 }
1086
1087 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1088 $dao = CRM_Core_DAO::executeQuery($query, $input);
1089 $result = FALSE;
1090 while ($dao->fetch()) {
1091 $duplicates[] = $dao->id;
1092 $result = TRUE;
1093 }
1094 return $result;
1095 }
1096
1097 /**
1098 * Takes an associative array and creates a contribution_product object.
1099 *
1100 * the function extract all the params it needs to initialize the create a
1101 * contribution_product object. the params array could contain additional unused name/value
1102 * pairs
1103 *
1104 * @param array $params
1105 * (reference) an assoc array of name/value pairs.
1106 *
1107 * @return CRM_Contribute_DAO_ContributionProduct
1108 */
1109 public static function addPremium(&$params) {
1110 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1111 $contributionProduct->copyValues($params);
1112 return $contributionProduct->save();
1113 }
1114
1115 /**
1116 * Get list of contribution fields for profile.
1117 * For now we only allow custom contribution fields to be in
1118 * profile
1119 *
1120 * @param bool $addExtraFields
1121 * True if special fields needs to be added.
1122 *
1123 * @return array
1124 * the list of contribution fields
1125 */
1126 public static function getContributionFields($addExtraFields = TRUE) {
1127 $contributionFields = CRM_Contribute_DAO_Contribution::export();
1128 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
1129
1130 if ($addExtraFields) {
1131 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
1132 }
1133
1134 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
1135
1136 foreach ($contributionFields as $key => $var) {
1137 if ($key == 'contribution_contact_id') {
1138 continue;
1139 }
1140 elseif ($key == 'contribution_campaign_id') {
1141 $var['title'] = ts('Campaign');
1142 }
1143 $fields[$key] = $var;
1144 }
1145
1146 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
1147 return $fields;
1148 }
1149
1150 /**
1151 * Add extra fields specific to contribution.
1152 */
1153 public static function getSpecialContributionFields() {
1154 $extraFields = array(
1155 'contribution_soft_credit_name' => array(
1156 'name' => 'contribution_soft_credit_name',
1157 'title' => 'Soft Credit Name',
1158 'headerPattern' => '/^soft_credit_name$/i',
1159 'where' => 'civicrm_contact_d.display_name',
1160 ),
1161 'contribution_soft_credit_email' => array(
1162 'name' => 'contribution_soft_credit_email',
1163 'title' => 'Soft Credit Email',
1164 'headerPattern' => '/^soft_credit_email$/i',
1165 'where' => 'soft_email.email',
1166 ),
1167 'contribution_soft_credit_phone' => array(
1168 'name' => 'contribution_soft_credit_phone',
1169 'title' => 'Soft Credit Phone',
1170 'headerPattern' => '/^soft_credit_phone$/i',
1171 'where' => 'soft_phone.phone',
1172 ),
1173 'contribution_soft_credit_contact_id' => array(
1174 'name' => 'contribution_soft_credit_contact_id',
1175 'title' => 'Soft Credit Contact ID',
1176 'headerPattern' => '/^soft_credit_contact_id$/i',
1177 'where' => 'civicrm_contribution_soft.contact_id',
1178 ),
1179 'contribution_pcp_title' => array(
1180 'name' => 'contribution_pcp_title',
1181 'title' => 'Personal Campaign Page Title',
1182 'headerPattern' => '/^contribution_pcp_title$/i',
1183 'where' => 'contribution_pcp.title',
1184 ),
1185 );
1186
1187 return $extraFields;
1188 }
1189
1190 /**
1191 * @param int $pageID
1192 *
1193 * @return array
1194 */
1195 public static function getCurrentandGoalAmount($pageID) {
1196 $query = "
1197 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1198 FROM civicrm_contribution_page p,
1199 civicrm_contribution c
1200 WHERE p.id = c.contribution_page_id
1201 AND p.id = %1
1202 AND c.cancel_date is null
1203 GROUP BY p.id
1204 ";
1205
1206 $config = CRM_Core_Config::singleton();
1207 $params = array(1 => array($pageID, 'Integer'));
1208 $dao = CRM_Core_DAO::executeQuery($query, $params);
1209
1210 if ($dao->fetch()) {
1211 return array($dao->goal, $dao->total);
1212 }
1213 else {
1214 return array(NULL, NULL);
1215 }
1216 }
1217
1218 /**
1219 * Get list of contributions which credit the passed in contact ID.
1220 *
1221 * The returned array provides details about the original contribution & donor.
1222 *
1223 * @todo - this is a confusing function called from one place. It has a test. It would be
1224 * nice to deprecate it.
1225 *
1226 * @param int $honorId
1227 * In Honor of Contact ID.
1228 *
1229 * @return array
1230 * list of contribution fields
1231 */
1232 public static function getHonorContacts($honorId) {
1233 $params = array();
1234 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1235 $honorDAO->contact_id = $honorId;
1236 $honorDAO->find();
1237
1238 $type = CRM_Contribute_PseudoConstant::financialType();
1239
1240 while ($honorDAO->fetch()) {
1241 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1242 $contributionDAO->id = $honorDAO->contribution_id;
1243
1244 if ($contributionDAO->find(TRUE)) {
1245 $params[$contributionDAO->id]['honor_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id);
1246 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
1247 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
1248 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
1249 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
1250 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
1251 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
1252 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
1253 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id);
1254 }
1255 }
1256
1257 return $params;
1258 }
1259
1260 /**
1261 * Get the sort name of a contact for a particular contribution.
1262 *
1263 * @param int $id
1264 * Id of the contribution.
1265 *
1266 * @return null|string
1267 * sort name of the contact if found
1268 */
1269 public static function sortName($id) {
1270 $id = CRM_Utils_Type::escape($id, 'Integer');
1271
1272 $query = "
1273 SELECT civicrm_contact.sort_name
1274 FROM civicrm_contribution, civicrm_contact
1275 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1276 AND civicrm_contribution.id = {$id}
1277 ";
1278 return CRM_Core_DAO::singleValueQuery($query);
1279 }
1280
1281 /**
1282 * @param int $contactID
1283 *
1284 * @return array
1285 */
1286 public static function annual($contactID) {
1287 if (is_array($contactID)) {
1288 $contactIDs = implode(',', $contactID);
1289 }
1290 else {
1291 $contactIDs = $contactID;
1292 }
1293
1294 $config = CRM_Core_Config::singleton();
1295 $startDate = $endDate = NULL;
1296
1297 $currentMonth = date('m');
1298 $currentDay = date('d');
1299 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1300 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1301 (int ) $config->fiscalYearStart['d'] > $currentDay
1302 )
1303 ) {
1304 $year = date('Y') - 1;
1305 }
1306 else {
1307 $year = date('Y');
1308 }
1309 $nextYear = $year + 1;
1310
1311 if ($config->fiscalYearStart) {
1312 $newFiscalYearStart = $config->fiscalYearStart;
1313 if ($newFiscalYearStart['M'] < 10) {
1314 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1315 }
1316 if ($newFiscalYearStart['d'] < 10) {
1317 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1318 }
1319 $config->fiscalYearStart = $newFiscalYearStart;
1320 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
1321 }
1322 else {
1323 $monthDay = '0101';
1324 }
1325 $startDate = "$year$monthDay";
1326 $endDate = "$nextYear$monthDay";
1327 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
1328 $additionalWhere = " AND b.financial_type_id IN (0)";
1329 $liWhere = " AND i.financial_type_id IN (0)";
1330 if (!empty($financialTypes)) {
1331 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1332 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1333 }
1334 $query = "
1335 SELECT count(*) as count,
1336 sum(total_amount) as amount,
1337 avg(total_amount) as average,
1338 currency
1339 FROM civicrm_contribution b
1340 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1341 WHERE b.contact_id IN ( $contactIDs )
1342 AND b.contribution_status_id = 1
1343 AND b.is_test = 0
1344 AND b.receive_date >= $startDate
1345 AND b.receive_date < $endDate
1346 $additionalWhere
1347 GROUP BY currency
1348 ";
1349 $dao = CRM_Core_DAO::executeQuery($query);
1350 $count = 0;
1351 $amount = $average = array();
1352 while ($dao->fetch()) {
1353 if ($dao->count > 0 && $dao->amount > 0) {
1354 $count += $dao->count;
1355 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1356 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1357 }
1358 }
1359 if ($count > 0) {
1360 return array(
1361 $count,
1362 implode(',&nbsp;', $amount),
1363 implode(',&nbsp;', $average),
1364 );
1365 }
1366 return array(0, 0, 0);
1367 }
1368
1369 /**
1370 * Check if there is a contribution with the params passed in.
1371 *
1372 * Used for trxn_id,invoice_id and contribution_id
1373 *
1374 * @param array $params
1375 * An assoc array of name/value pairs.
1376 *
1377 * @return array
1378 * contribution id if success else NULL
1379 */
1380 public static function checkDuplicateIds($params) {
1381 $dao = new CRM_Contribute_DAO_Contribution();
1382
1383 $clause = array();
1384 $input = array();
1385 foreach ($params as $k => $v) {
1386 if ($v) {
1387 $clause[] = "$k = '$v'";
1388 }
1389 }
1390 $clause = implode(' AND ', $clause);
1391 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1392 $dao = CRM_Core_DAO::executeQuery($query, $input);
1393
1394 while ($dao->fetch()) {
1395 $result = $dao->id;
1396 return $result;
1397 }
1398 return NULL;
1399 }
1400
1401 /**
1402 * Get the contribution details for component export.
1403 *
1404 * @param int $exportMode
1405 * Export mode.
1406 * @param string $componentIds
1407 * Component ids.
1408 *
1409 * @return array
1410 * associated array
1411 */
1412 public static function getContributionDetails($exportMode, $componentIds) {
1413 $paymentDetails = array();
1414 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1415
1416 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1417 $componentSelect = " civicrm_participant_payment.participant_id id";
1418 $additionalClause = "
1419 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1420 AND civicrm_participant_payment.participant_id {$componentClause} )
1421 ";
1422 }
1423 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1424 $componentSelect = " civicrm_membership_payment.membership_id id";
1425 $additionalClause = "
1426 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1427 AND civicrm_membership_payment.membership_id {$componentClause} )
1428 ";
1429 }
1430 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1431 $componentSelect = " civicrm_pledge_payment.id id";
1432 $additionalClause = "
1433 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1434 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1435 ";
1436 }
1437
1438 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1439 trxn_id, {$componentSelect}
1440 FROM civicrm_contribution
1441 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1442 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1443 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1444 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1445 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1446 AND option_group_contribution_status.id = contribution_status.option_group_id )
1447 {$additionalClause}
1448 ";
1449
1450 $dao = CRM_Core_DAO::executeQuery($query);
1451
1452 while ($dao->fetch()) {
1453 $paymentDetails[$dao->id] = array(
1454 'total_amount' => $dao->total_amount,
1455 'contribution_status' => $dao->status,
1456 'receive_date' => $dao->receive_date,
1457 'pay_instru' => $dao->payment_instrument,
1458 'trxn_id' => $dao->trxn_id,
1459 );
1460 }
1461
1462 return $paymentDetails;
1463 }
1464
1465 /**
1466 * Create address associated with contribution record.
1467 *
1468 * As long as there is one or more billing field in the parameters we will create the address.
1469 *
1470 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1471 * thought).
1472 *
1473 * @param array $params
1474 * @param int $billingLocationTypeID
1475 *
1476 * @return int
1477 * address id
1478 */
1479 public static function createAddress($params, $billingLocationTypeID) {
1480 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
1481 if ($hasBillingField) {
1482 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
1483 return $address->id;
1484 }
1485 return NULL;
1486
1487 }
1488
1489 /**
1490 * Delete billing address record related contribution.
1491 *
1492 * @param int $contributionId
1493 * @param int $contactId
1494 */
1495 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1496 $clauses = array();
1497 $contactJoin = NULL;
1498
1499 if ($contributionId) {
1500 $clauses[] = "cc.id = {$contributionId}";
1501 }
1502
1503 if ($contactId) {
1504 $clauses[] = "cco.id = {$contactId}";
1505 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1506 }
1507
1508 if (empty($clauses)) {
1509 CRM_Core_Error::fatal();
1510 }
1511
1512 $condition = implode(' OR ', $clauses);
1513
1514 $query = "
1515 SELECT ca.id
1516 FROM civicrm_address ca
1517 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1518 $contactJoin
1519 WHERE $condition
1520 ";
1521 $dao = CRM_Core_DAO::executeQuery($query);
1522
1523 while ($dao->fetch()) {
1524 $params = array('id' => $dao->id);
1525 CRM_Core_BAO_Block::blockDelete('Address', $params);
1526 }
1527 }
1528
1529 /**
1530 * This function check online pending contribution associated w/
1531 * Online Event Registration or Online Membership signup.
1532 *
1533 * @param int $componentId
1534 * Participant/membership id.
1535 * @param string $componentName
1536 * Event/Membership.
1537 *
1538 * @return int
1539 * pending contribution id.
1540 */
1541 public static function checkOnlinePendingContribution($componentId, $componentName) {
1542 $contributionId = NULL;
1543 if (!$componentId ||
1544 !in_array($componentName, array('Event', 'Membership'))
1545 ) {
1546 return $contributionId;
1547 }
1548
1549 if ($componentName == 'Event') {
1550 $idName = 'participant_id';
1551 $componentTable = 'civicrm_participant';
1552 $paymentTable = 'civicrm_participant_payment';
1553 $source = ts('Online Event Registration');
1554 }
1555
1556 if ($componentName == 'Membership') {
1557 $idName = 'membership_id';
1558 $componentTable = 'civicrm_membership';
1559 $paymentTable = 'civicrm_membership_payment';
1560 $source = ts('Online Contribution');
1561 }
1562
1563 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1564
1565 $query = "
1566 SELECT component.id as {$idName},
1567 componentPayment.contribution_id as contribution_id,
1568 contribution.source source,
1569 contribution.contribution_status_id as contribution_status_id,
1570 contribution.is_pay_later as is_pay_later
1571 FROM $componentTable component
1572 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1573 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1574 WHERE component.id = {$componentId}";
1575
1576 $dao = CRM_Core_DAO::executeQuery($query);
1577
1578 while ($dao->fetch()) {
1579 if ($dao->contribution_id &&
1580 $dao->is_pay_later &&
1581 $dao->contribution_status_id == $pendingStatusId &&
1582 strpos($dao->source, $source) !== FALSE
1583 ) {
1584 $contributionId = $dao->contribution_id;
1585 $dao->free();
1586 }
1587 }
1588
1589 return $contributionId;
1590 }
1591
1592 /**
1593 * Update contribution as well as related objects.
1594 *
1595 * This function by-passes hooks - to address this - don't use this function.
1596 *
1597 * @deprecated
1598 *
1599 * Use api contribute.completetransaction
1600 * For failures use failPayment (preferably exposing by api in the process).
1601 *
1602 * @param array $params
1603 * @param bool $processContributionObject
1604 *
1605 * @return array
1606 * @throws \Exception
1607 */
1608 public static function transitionComponents($params, $processContributionObject = FALSE) {
1609 // get minimum required values.
1610 $contactId = CRM_Utils_Array::value('contact_id', $params);
1611 $componentId = CRM_Utils_Array::value('component_id', $params);
1612 $componentName = CRM_Utils_Array::value('componentName', $params);
1613 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1614 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1615
1616 // if we already processed contribution object pass previous status id.
1617 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1618
1619 $updateResult = array();
1620
1621 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1622
1623 // we process only ( Completed, Cancelled, or Failed ) contributions.
1624 if (!$contributionId ||
1625 !in_array($contributionStatusId, array(
1626 array_search('Completed', $contributionStatuses),
1627 array_search('Cancelled', $contributionStatuses),
1628 array_search('Failed', $contributionStatuses),
1629 ))
1630 ) {
1631 return $updateResult;
1632 }
1633
1634 if (!$componentName || !$componentId) {
1635 // get the related component details.
1636 $componentDetails = self::getComponentDetails($contributionId);
1637 }
1638 else {
1639 $componentDetails['contact_id'] = $contactId;
1640 $componentDetails['component'] = $componentName;
1641
1642 if ($componentName == 'event') {
1643 $componentDetails['participant'] = $componentId;
1644 }
1645 else {
1646 $componentDetails['membership'] = $componentId;
1647 }
1648 }
1649
1650 if (!empty($componentDetails['contact_id'])) {
1651 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1652 $contributionId,
1653 'contact_id'
1654 );
1655 }
1656
1657 // do check for required ids.
1658 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
1659 return $updateResult;
1660 }
1661
1662 //now we are ready w/ required ids, start processing.
1663
1664 $baseIPN = new CRM_Core_Payment_BaseIPN();
1665
1666 $input = $ids = $objects = array();
1667
1668 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1669 $ids['contribution'] = $contributionId;
1670 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1671 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1672 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1673 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1674 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1675 $ids['contributionRecur'] = NULL;
1676 $ids['contributionPage'] = NULL;
1677
1678 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1679 CRM_Core_Error::fatal();
1680 }
1681
1682 $memberships = &$objects['membership'];
1683 $participant = &$objects['participant'];
1684 $pledgePayment = &$objects['pledge_payment'];
1685 $contribution = &$objects['contribution'];
1686
1687 if ($pledgePayment) {
1688 $pledgePaymentIDs = array();
1689 foreach ($pledgePayment as $key => $object) {
1690 $pledgePaymentIDs[] = $object->id;
1691 }
1692 $pledgeID = $pledgePayment[0]->pledge_id;
1693 }
1694
1695 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1696
1697 if ($participant) {
1698 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1699 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1700 $participant->id,
1701 'status_id'
1702 );
1703 }
1704 // we might want to process contribution object.
1705 $processContribution = FALSE;
1706 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1707 if (is_array($memberships)) {
1708 foreach ($memberships as $membership) {
1709 if ($membership) {
1710 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1711 $membership->save();
1712
1713 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1714 if ($processContributionObject) {
1715 $processContribution = TRUE;
1716 }
1717 }
1718 }
1719 }
1720
1721 if ($participant) {
1722 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1723 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1724
1725 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1726 if ($processContributionObject) {
1727 $processContribution = TRUE;
1728 }
1729 }
1730
1731 if ($pledgePayment) {
1732 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1733
1734 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1735 if ($processContributionObject) {
1736 $processContribution = TRUE;
1737 }
1738 }
1739 }
1740 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1741 if (is_array($memberships)) {
1742 foreach ($memberships as $membership) {
1743 if ($membership) {
1744 $membership->status_id = array_search('Expired', $membershipStatuses);
1745 $membership->save();
1746
1747 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1748 if ($processContributionObject) {
1749 $processContribution = TRUE;
1750 }
1751 }
1752 }
1753 }
1754 if ($participant) {
1755 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1756 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1757
1758 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1759 if ($processContributionObject) {
1760 $processContribution = TRUE;
1761 }
1762 }
1763
1764 if ($pledgePayment) {
1765 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1766
1767 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1768 if ($processContributionObject) {
1769 $processContribution = TRUE;
1770 }
1771 }
1772 }
1773 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1774
1775 // only pending contribution related object processed.
1776 if ($previousContriStatusId &&
1777 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1778 ) {
1779 // this is case when we already processed contribution object.
1780 return $updateResult;
1781 }
1782 elseif (!$previousContriStatusId &&
1783 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1784 ) {
1785 // this is case when we are going to process contribution object later.
1786 return $updateResult;
1787 }
1788
1789 if (is_array($memberships)) {
1790 foreach ($memberships as $membership) {
1791 if ($membership) {
1792 $format = '%Y%m%d';
1793
1794 //CRM-4523
1795 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1796 $membership->membership_type_id,
1797 $membership->is_test, $membership->id
1798 );
1799
1800 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1801 // this picks up membership type changes during renewals
1802 $sql = "
1803 SELECT membership_type_id
1804 FROM civicrm_membership_log
1805 WHERE membership_id=$membership->id
1806 ORDER BY id DESC
1807 LIMIT 1;";
1808 $dao = new CRM_Core_DAO();
1809 $dao->query($sql);
1810 if ($dao->fetch()) {
1811 if (!empty($dao->membership_type_id)) {
1812 $membership->membership_type_id = $dao->membership_type_id;
1813 $membership->save();
1814 }
1815 }
1816 // else fall back to using current membership type
1817 $dao->free();
1818
1819 // Figure out number of terms
1820 $numterms = 1;
1821 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1822 foreach ($lineitems as $lineitem) {
1823 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1824 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
1825
1826 // in case membership_num_terms comes through as null or zero
1827 $numterms = $numterms >= 1 ? $numterms : 1;
1828 break;
1829 }
1830 }
1831
1832 // CRM-15735-to update the membership status as per the contribution receive date
1833 $joinDate = NULL;
1834 if (!empty($params['receive_date'])) {
1835 $joinDate = $params['receive_date'];
1836 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
1837 $membership->end_date,
1838 $membership->join_date,
1839 $params['receive_date'],
1840 FALSE,
1841 $membership->membership_type_id,
1842 (array) $membership
1843 );
1844 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
1845 $membership->save();
1846 }
1847
1848 if ($currentMembership) {
1849 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1850 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1851 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1852 }
1853 else {
1854 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
1855 }
1856
1857 //get the status for membership.
1858 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1859 $dates['end_date'],
1860 $dates['join_date'],
1861 'today',
1862 TRUE,
1863 $membership->membership_type_id,
1864 (array) $membership
1865 );
1866
1867 $formattedParams = array(
1868 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1869 array_search('Current', $membershipStatuses)
1870 ),
1871 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1872 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1873 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1874 );
1875
1876 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
1877
1878 $membership->copyValues($formattedParams);
1879 $membership->save();
1880
1881 //updating the membership log
1882 $membershipLog = array();
1883 $membershipLog = $formattedParams;
1884 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1885 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
1886
1887 $membershipLog['start_date'] = $logStartDate;
1888 $membershipLog['membership_id'] = $membership->id;
1889 $membershipLog['modified_id'] = $membership->contact_id;
1890 $membershipLog['modified_date'] = date('Ymd');
1891 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1892
1893 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1894
1895 //update related Memberships.
1896 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
1897
1898 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1899 '%B %E%f, %Y'
1900 );
1901 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1902 if ($processContributionObject) {
1903 $processContribution = TRUE;
1904 }
1905
1906 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1907 }
1908 }
1909 }
1910
1911 if ($participant) {
1912 $updatedStatusId = array_search('Registered', $participantStatuses);
1913 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1914
1915 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1916 if ($processContributionObject) {
1917 $processContribution = TRUE;
1918 }
1919 }
1920
1921 if ($pledgePayment) {
1922 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1923
1924 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1925 if ($processContributionObject) {
1926 $processContribution = TRUE;
1927 }
1928 }
1929 }
1930
1931 // process contribution object.
1932 if ($processContribution) {
1933 $contributionParams = array();
1934 $fields = array(
1935 'contact_id',
1936 'total_amount',
1937 'receive_date',
1938 'is_test',
1939 'campaign_id',
1940 'payment_instrument_id',
1941 'trxn_id',
1942 'invoice_id',
1943 'financial_type_id',
1944 'contribution_status_id',
1945 'non_deductible_amount',
1946 'receipt_date',
1947 'check_number',
1948 );
1949 foreach ($fields as $field) {
1950 if (empty($params[$field])) {
1951 continue;
1952 }
1953 $contributionParams[$field] = $params[$field];
1954 }
1955
1956 $ids = array('contribution' => $contributionId);
1957 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1958 }
1959
1960 return $updateResult;
1961 }
1962
1963 /**
1964 * Returns all contribution related object ids.
1965 *
1966 * @param $contributionId
1967 *
1968 * @return array
1969 */
1970 public static function getComponentDetails($contributionId) {
1971 $componentDetails = $pledgePayment = array();
1972 if (!$contributionId) {
1973 return $componentDetails;
1974 }
1975
1976 $query = "
1977 SELECT c.id as contribution_id,
1978 c.contact_id as contact_id,
1979 c.contribution_recur_id,
1980 mp.membership_id as membership_id,
1981 m.membership_type_id as membership_type_id,
1982 pp.participant_id as participant_id,
1983 p.event_id as event_id,
1984 pgp.id as pledge_payment_id
1985 FROM civicrm_contribution c
1986 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1987 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1988 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1989 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1990 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1991 WHERE c.id = $contributionId";
1992
1993 $dao = CRM_Core_DAO::executeQuery($query);
1994 $componentDetails = array();
1995
1996 while ($dao->fetch()) {
1997 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1998 $componentDetails['contact_id'] = $dao->contact_id;
1999 if ($dao->event_id) {
2000 $componentDetails['event'] = $dao->event_id;
2001 }
2002 if ($dao->participant_id) {
2003 $componentDetails['participant'] = $dao->participant_id;
2004 }
2005 if ($dao->membership_id) {
2006 if (!isset($componentDetails['membership'])) {
2007 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2008 }
2009 $componentDetails['membership'][] = $dao->membership_id;
2010 $componentDetails['membership_type'][] = $dao->membership_type_id;
2011 }
2012 if ($dao->pledge_payment_id) {
2013 $pledgePayment[] = $dao->pledge_payment_id;
2014 }
2015 if ($dao->contribution_recur_id) {
2016 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
2017 }
2018 }
2019
2020 if ($pledgePayment) {
2021 $componentDetails['pledge_payment'] = $pledgePayment;
2022 }
2023
2024 return $componentDetails;
2025 }
2026
2027 /**
2028 * @param int $contactId
2029 * @param bool $includeSoftCredit
2030 *
2031 * @return null|string
2032 */
2033 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2034 if (!$contactId) {
2035 return 0;
2036 }
2037 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
2038 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2039 $liWhere = " AND i.financial_type_id IN (0)";
2040 if (!empty($financialTypes)) {
2041 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2042 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2043 }
2044 $contactContributionsSQL = "
2045 SELECT contribution.id AS id
2046 FROM civicrm_contribution contribution
2047 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2048 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2049 $additionalWhere
2050 AND i.id IS NULL";
2051
2052 $contactSoftCreditContributionsSQL = "
2053 SELECT contribution.id
2054 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2055 ON ( contribution.id = softContribution.contribution_id )
2056 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2057 $query = "SELECT count( x.id ) count FROM ( ";
2058 $query .= $contactContributionsSQL;
2059
2060 if ($includeSoftCredit) {
2061 $query .= " UNION ";
2062 $query .= $contactSoftCreditContributionsSQL;
2063 }
2064
2065 $query .= ") x";
2066
2067 return CRM_Core_DAO::singleValueQuery($query);
2068 }
2069
2070 /**
2071 * Repeat a transaction as part of a recurring series.
2072 *
2073 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2074 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2075 * subsequent call to the contribution.completetransaction api.
2076 *
2077 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2078 *
2079 * @param CRM_Contribute_BAO_Contribution $contribution
2080 * @param array $input
2081 * @param array $contributionParams
2082 * @param int $paymentProcessorID
2083 *
2084 * @return array
2085 * @throws CiviCRM_API3_Exception
2086 */
2087 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2088 if (!empty($contribution->id)) {
2089 return FALSE;
2090 }
2091 if (empty($contribution->id)) {
2092 // Unclear why this would only be set for repeats.
2093 if (!empty($input['amount'])) {
2094 $contribution->total_amount = $contributionParams['total_amount'] = $input['amount'];
2095 }
2096
2097 if (!empty($contributionParams['contribution_recur_id'])) {
2098 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2099 'id' => $contributionParams['contribution_recur_id'],
2100 ));
2101 if (!empty($recurringContribution['campaign_id'])) {
2102 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2103 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2104 }
2105 if (!empty($recurringContribution['financial_type_id'])) {
2106 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2107 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2108 }
2109 }
2110 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution(
2111 $contributionParams['contribution_recur_id'],
2112 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2113 );
2114 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2115
2116 $contributionParams['status_id'] = 'Pending';
2117 if (isset($contributionParams['financial_type_id'])) {
2118 // Give precedence to passed in type.
2119 $contribution->financial_type_id = $contributionParams['financial_type_id'];
2120 }
2121 else {
2122 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2123 }
2124 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2125 $contributionParams['source'] = empty($templateContribution['source']) ? ts('Recurring contribution') : $templateContribution['source'];
2126
2127 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2128 //do not create CC or BCC emails or profile notifications.
2129 //The if is just to be safe. Not sure if we can ever arrive with this unset
2130 if (isset($contribution->contribution_page_id)) {
2131 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id;
2132 }
2133
2134 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2135 $contribution->id = $createContribution['id'];
2136 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id);
2137 return TRUE;
2138 }
2139 }
2140
2141 /**
2142 * Get individual id for onbehalf contribution.
2143 *
2144 * @param int $contributionId
2145 * Contribution id.
2146 * @param int $contributorId
2147 * Contributor id.
2148 *
2149 * @return array
2150 * containing organization id and individual id
2151 */
2152 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2153
2154 $ids = array();
2155
2156 if (!$contributionId) {
2157 return $ids;
2158 }
2159
2160 // fetch contributor id if null
2161 if (!$contributorId) {
2162 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2163 $contributionId, 'contact_id'
2164 );
2165 }
2166
2167 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2168 $activityTypeId = array_search('Contribution', $activityTypeIds);
2169
2170 if ($activityTypeId && $contributorId) {
2171 $activityQuery = "
2172 SELECT civicrm_activity_contact.contact_id
2173 FROM civicrm_activity_contact
2174 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2175 WHERE civicrm_activity.activity_type_id = %1
2176 AND civicrm_activity.source_record_id = %2
2177 AND civicrm_activity_contact.record_type_id = %3
2178 ";
2179
2180 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2181 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2182
2183 $params = array(
2184 1 => array($activityTypeId, 'Integer'),
2185 2 => array($contributionId, 'Integer'),
2186 3 => array($sourceID, 'Integer'),
2187 );
2188
2189 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
2190
2191 // for on behalf contribution source is individual and contributor is organization
2192 if ($sourceContactId && $sourceContactId != $contributorId) {
2193 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
2194 // get rel type id for employee of relation
2195 foreach ($relationshipTypeIds as $id => $typeVals) {
2196 if ($typeVals['name_a_b'] == 'Employee of') {
2197 $relationshipTypeId = $id;
2198 break;
2199 }
2200 }
2201
2202 $rel = new CRM_Contact_DAO_Relationship();
2203 $rel->relationship_type_id = $relationshipTypeId;
2204 $rel->contact_id_a = $sourceContactId;
2205 $rel->contact_id_b = $contributorId;
2206 if ($rel->find(TRUE)) {
2207 $ids['individual_id'] = $rel->contact_id_a;
2208 $ids['organization_id'] = $rel->contact_id_b;
2209 }
2210 }
2211 }
2212
2213 return $ids;
2214 }
2215
2216 /**
2217 * @return array
2218 */
2219 public static function getContributionDates() {
2220 $config = CRM_Core_Config::singleton();
2221 $currentMonth = date('m');
2222 $currentDay = date('d');
2223 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2224 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2225 (int ) $config->fiscalYearStart['d'] > $currentDay
2226 )
2227 ) {
2228 $year = date('Y') - 1;
2229 }
2230 else {
2231 $year = date('Y');
2232 }
2233 $year = array('Y' => $year);
2234 $yearDate = $config->fiscalYearStart;
2235 $yearDate = array_merge($year, $yearDate);
2236 $yearDate = CRM_Utils_Date::format($yearDate);
2237
2238 $monthDate = date('Ym') . '01';
2239
2240 $now = date('Ymd');
2241
2242 return array(
2243 'now' => $now,
2244 'yearDate' => $yearDate,
2245 'monthDate' => $monthDate,
2246 );
2247 }
2248
2249 /**
2250 * Load objects relations to contribution object.
2251 * Objects are stored in the $_relatedObjects property
2252 * In the first instance we are just moving functionality from BASEIpn -
2253 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2254 *
2255 * Note that the unit test for the BaseIPN class tests this function
2256 *
2257 * @param array $input
2258 * Input as delivered from Payment Processor.
2259 * @param array $ids
2260 * Ids as Loaded by Payment Processor.
2261 * @param bool $loadAll
2262 * Load all related objects - even where id not passed in? (allows API to call this).
2263 *
2264 * @return bool
2265 * @throws Exception
2266 */
2267 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2268 if ($loadAll) {
2269 $ids = array_merge($this->getComponentDetails($this->id), $ids);
2270 if (empty($ids['contact']) && isset($this->contact_id)) {
2271 $ids['contact'] = $this->contact_id;
2272 }
2273 }
2274 if (empty($this->_component)) {
2275 if (!empty($ids['event'])) {
2276 $this->_component = 'event';
2277 }
2278 else {
2279 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2280 }
2281 }
2282
2283 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2284 // refactoring than anything else, and has unit test coverage.
2285 if (empty($this->financial_type_id)) {
2286 $this->find(TRUE);
2287 }
2288
2289 $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value(
2290 'paymentProcessor',
2291 $ids
2292 ));
2293
2294 if (!$paymentProcessorID && $this->contribution_page_id) {
2295 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2296 $this->contribution_page_id,
2297 'payment_processor'
2298 );
2299 if ($paymentProcessorID) {
2300 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2301 }
2302 }
2303
2304 $ids['contributionType'] = $this->financial_type_id;
2305 $ids['financialType'] = $this->financial_type_id;
2306
2307 $entities = array(
2308 'contact' => 'CRM_Contact_BAO_Contact',
2309 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2310 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2311 'financialType' => 'CRM_Financial_BAO_FinancialType',
2312 );
2313 foreach ($entities as $entity => $bao) {
2314 if (!empty($ids[$entity])) {
2315 $this->_relatedObjects[$entity] = new $bao();
2316 $this->_relatedObjects[$entity]->id = $ids[$entity];
2317 if (!$this->_relatedObjects[$entity]->find(TRUE)) {
2318 throw new CRM_Core_Exception($entity . ' could not be loaded');
2319 }
2320 }
2321 }
2322
2323 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2324 $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
2325 }
2326
2327 if (!empty($ids['pledge_payment'])) {
2328 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2329 if (empty($paymentID)) {
2330 continue;
2331 }
2332 $payment = new CRM_Pledge_BAO_PledgePayment();
2333 $payment->id = $paymentID;
2334 if (!$payment->find(TRUE)) {
2335 throw new Exception("Could not find pledge payment record: " . $paymentID);
2336 }
2337 $this->_relatedObjects['pledge_payment'][] = $payment;
2338 }
2339 }
2340
2341 $this->loadRelatedMembershipObjects($ids);
2342
2343 if ($this->_component != 'contribute') {
2344 // we are in event mode
2345 // make sure event exists and is valid
2346 $event = new CRM_Event_BAO_Event();
2347 $event->id = $ids['event'];
2348 if ($ids['event'] &&
2349 !$event->find(TRUE)
2350 ) {
2351 throw new Exception("Could not find event: " . $ids['event']);
2352 }
2353
2354 $this->_relatedObjects['event'] = &$event;
2355
2356 $participant = new CRM_Event_BAO_Participant();
2357 $participant->id = $ids['participant'];
2358 if ($ids['participant'] &&
2359 !$participant->find(TRUE)
2360 ) {
2361 throw new Exception("Could not find participant: " . $ids['participant']);
2362 }
2363 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2364
2365 $this->_relatedObjects['participant'] = &$participant;
2366
2367 // get the payment processor id from event - this is inaccurate see CRM-16923
2368 // in future we should look at throwing an exception here rather than an dubious guess.
2369 if (!$paymentProcessorID) {
2370 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2371 if ($paymentProcessorID) {
2372 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2373 }
2374 }
2375 }
2376
2377 if ($paymentProcessorID) {
2378 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2379 $this->is_test ? 'test' : 'live'
2380 );
2381 $ids['paymentProcessor'] = $paymentProcessorID;
2382 $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
2383 }
2384 return TRUE;
2385 }
2386
2387 /**
2388 * Create array of message information - ie. return html version, txt version, to field
2389 *
2390 * @param array $input
2391 * Incoming information.
2392 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2393 * just check presence of recur object but maintaining legacy approach
2394 * to be careful)
2395 * @param array $ids
2396 * IDs of related objects.
2397 * @param array $values
2398 * Any values that may have already been compiled by calling process.
2399 * This is augmented by values 'gathered' by gatherMessageValues
2400 * @param bool $recur
2401 * @param bool $returnMessageText
2402 * Distinguishes between whether to send message or return.
2403 * message text. We are working towards this function ALWAYS returning message text & calling
2404 * function doing emails / pdfs with it
2405 *
2406 * @return array
2407 * messages
2408 * @throws Exception
2409 */
2410 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2411 $this->loadRelatedObjects($input, $ids);
2412
2413 if (empty($this->_component)) {
2414 $this->_component = CRM_Utils_Array::value('component', $input);
2415 }
2416
2417 //not really sure what params might be passed in but lets merge em into values
2418 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2419 if (!empty($input['receipt_date'])) {
2420 $values['receipt_date'] = $input['receipt_date'];
2421 }
2422
2423 $template = CRM_Core_Smarty::singleton();
2424 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2425 //what does recur 'mean here - to do with payment processor return functionality but
2426 // what is the importance
2427 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2428 $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']);
2429
2430 $entityID = $entity = NULL;
2431 if (isset($ids['contribution'])) {
2432 $entity = 'contribution';
2433 $entityID = $ids['contribution'];
2434 }
2435 if (!empty($ids['membership'])) {
2436 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2437 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2438 // line having loaded an array
2439 $ids['membership'] = (array) $ids['membership'];
2440 $entity = 'membership';
2441 $entityID = $ids['membership'][0];
2442 }
2443
2444 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2445 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2446 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2447
2448 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2449 //direct mode showing billing block, so use directIPN for temporary
2450 $template->assign('contributeMode', 'directIPN');
2451 }
2452 }
2453 // todo remove strtolower - check consistency
2454 if (strtolower($this->_component) == 'event') {
2455 $eventParams = array('id' => $this->_relatedObjects['participant']->event_id);
2456 $values['event'] = array();
2457
2458 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2459
2460 //get location details
2461 $locationParams = array('entity_id' => $this->_relatedObjects['participant']->event_id, 'entity_table' => 'civicrm_event');
2462 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2463
2464 $ufJoinParams = array(
2465 'entity_table' => 'civicrm_event',
2466 'entity_id' => $ids['event'],
2467 'module' => 'CiviEvent',
2468 );
2469
2470 list($custom_pre_id,
2471 $custom_post_ids
2472 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2473
2474 $values['custom_pre_id'] = $custom_pre_id;
2475 $values['custom_post_id'] = $custom_post_ids;
2476 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2477 //and cases involving status updation through ipn
2478 // whatever that means!
2479 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2480 // perhaps we should throw an e-notice if amount is set & force total_amount?
2481 if (!empty($input['amount'])) {
2482 $values['totalAmount'] = $input['amount'];
2483 }
2484
2485 if ($values['event']['is_email_confirm']) {
2486 $values['is_email_receipt'] = 1;
2487 }
2488
2489 if (!empty($ids['contribution'])) {
2490 $values['contributionId'] = $ids['contribution'];
2491 }
2492
2493 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2494 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2495 );
2496 }
2497 else {
2498 $values['contribution_id'] = $this->id;
2499 if (!empty($ids['related_contact'])) {
2500 $values['related_contact'] = $ids['related_contact'];
2501 if (isset($ids['onbehalf_dupe_alert'])) {
2502 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2503 }
2504 $entityBlock = array(
2505 'contact_id' => $ids['contact'],
2506 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2507 'Home', 'id', 'name'
2508 ),
2509 );
2510 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2511 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2512 }
2513 $isTest = FALSE;
2514 if ($this->is_test) {
2515 $isTest = TRUE;
2516 }
2517 if (!empty($this->_relatedObjects['membership'])) {
2518 foreach ($this->_relatedObjects['membership'] as $membership) {
2519 if ($membership->id) {
2520 $values['isMembership'] = TRUE;
2521 $values['membership_assign'] = TRUE;
2522
2523 // need to set the membership values here
2524 $template->assign('membership_name',
2525 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2526 );
2527 $template->assign('mem_start_date', $membership->start_date);
2528 $template->assign('mem_join_date', $membership->join_date);
2529 $template->assign('mem_end_date', $membership->end_date);
2530 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2531 $template->assign('mem_status', $membership_status);
2532 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2533 $values['is_pay_later'] = 1;
2534 }
2535
2536 // if separate payment there are two contributions recorded and the
2537 // admin will need to send a receipt for each of them separately.
2538 // we dont link the two in the db (but can potentially infer it if needed)
2539 $template->assign('is_separate_payment', 0);
2540
2541 if ($recur && $paymentObject) {
2542 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'cancel');
2543 $template->assign('cancelSubscriptionUrl', $url);
2544 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2545 $template->assign('updateSubscriptionBillingUrl', $url);
2546 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2547 $template->assign('updateSubscriptionUrl', $url);
2548 }
2549
2550 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2551
2552 return $result;
2553 // otherwise if its about sending emails, continue sending without return, as we
2554 // don't want to exit the loop.
2555 }
2556 }
2557 }
2558 else {
2559 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2560 }
2561 }
2562 }
2563
2564 /**
2565 * Gather values for contribution mail - this function has been created
2566 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2567 * Values related to the contribution in question are gathered
2568 *
2569 * @param array $input
2570 * Input into function (probably from payment processor).
2571 * @param array $values
2572 * @param array $ids
2573 * The set of ids related to the input.
2574 *
2575 * @return array
2576 */
2577 public function _gatherMessageValues($input, &$values, $ids = array()) {
2578 // set display address of contributor
2579 if ($this->address_id) {
2580 $addressParams = array('id' => $this->address_id);
2581 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2582 $addressDetails = array_values($addressDetails);
2583 }
2584 // Else we assign the billing address of the contribution contact.
2585 else {
2586 $addressParams = array('contact_id' => $this->contact_id, 'is_billing' => 1);
2587 $addressDetails = (array) CRM_Core_BAO_Address::getValues($addressParams);
2588 $addressDetails = array_values($addressDetails);
2589 }
2590
2591 if (!empty($addressDetails[0]['display'])) {
2592 $values['address'] = $addressDetails[0]['display'];
2593 }
2594
2595 if ($this->_component == 'contribute') {
2596 //get soft contributions
2597 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE);
2598 if (!empty($softContributions)) {
2599 $values['softContributions'] = $softContributions['soft_credit'];
2600 }
2601 if (isset($this->contribution_page_id)) {
2602 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2603 if ($this->contribution_page_id) {
2604 // CRM-8254 - override default currency if applicable
2605 $config = CRM_Core_Config::singleton();
2606 $config->defaultCurrency = CRM_Utils_Array::value(
2607 'currency',
2608 $values,
2609 $config->defaultCurrency
2610 );
2611 }
2612 }
2613 // no contribution page -probably back office
2614 else {
2615 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2616 $values['is_email_receipt'] = 1;
2617 $values['title'] = 'Contribution';
2618 }
2619 // set lineItem for contribution
2620 if ($this->id) {
2621 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2622 if (!empty($lineItem)) {
2623 $itemId = key($lineItem);
2624 foreach ($lineItem as &$eachItem) {
2625 if (isset($this->_relatedObjects['membership'])
2626 && is_array($this->_relatedObjects['membership'])
2627 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
2628 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2629 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2630 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2631 }
2632 }
2633 $values['lineItem'][0] = $lineItem;
2634 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2635 }
2636 }
2637
2638 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2639 $this->id,
2640 $this->contact_id
2641 );
2642 // if this is onbehalf of contribution then set related contact
2643 if (!empty($relatedContact['individual_id'])) {
2644 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2645 }
2646 }
2647 else {
2648 // event
2649 $eventParams = array(
2650 'id' => $this->_relatedObjects['event']->id,
2651 );
2652 $values['event'] = array();
2653
2654 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2655 // add custom fields for event
2656 $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this->_relatedObjects['event'], $this->_relatedObjects['event']->id);
2657
2658 $eventCustomGroup = array();
2659 foreach ($eventGroupTree as $key => $group) {
2660 if ($key === 'info') {
2661 continue;
2662 }
2663
2664 foreach ($group['fields'] as $k => $customField) {
2665 $groupLabel = $group['title'];
2666 if (!empty($customField['customValue'])) {
2667 foreach ($customField['customValue'] as $customFieldValues) {
2668 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2669 }
2670 }
2671 }
2672 }
2673 $values['event']['customGroup'] = $eventCustomGroup;
2674
2675 //get participant details
2676 $participantParams = array(
2677 'id' => $this->_relatedObjects['participant']->id,
2678 );
2679
2680 $values['participant'] = array();
2681
2682 CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds);
2683 // add custom fields for event
2684 $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this->_relatedObjects['participant'], $this->_relatedObjects['participant']->id);
2685 $participantCustomGroup = array();
2686 foreach ($participantGroupTree as $key => $group) {
2687 if ($key === 'info') {
2688 continue;
2689 }
2690
2691 foreach ($group['fields'] as $k => $customField) {
2692 $groupLabel = $group['title'];
2693 if (!empty($customField['customValue'])) {
2694 foreach ($customField['customValue'] as $customFieldValues) {
2695 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2696 }
2697 }
2698 }
2699 }
2700 $values['participant']['customGroup'] = $participantCustomGroup;
2701
2702 //get location details
2703 $locationParams = array(
2704 'entity_id' => $this->_relatedObjects['event']->id,
2705 'entity_table' => 'civicrm_event',
2706 );
2707 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2708
2709 $ufJoinParams = array(
2710 'entity_table' => 'civicrm_event',
2711 'entity_id' => $ids['event'],
2712 'module' => 'CiviEvent',
2713 );
2714
2715 list($custom_pre_id,
2716 $custom_post_ids
2717 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2718
2719 $values['custom_pre_id'] = $custom_pre_id;
2720 $values['custom_post_id'] = $custom_post_ids;
2721
2722 // set lineItem for event contribution
2723 if ($this->id) {
2724 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2725 if (!empty($participantIds)) {
2726 foreach ($participantIds as $pIDs) {
2727 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2728 if (!CRM_Utils_System::isNull($lineItem)) {
2729 $values['lineItem'][] = $lineItem;
2730 }
2731 }
2732 }
2733 }
2734 }
2735
2736 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $this->id);
2737
2738 $customGroup = array();
2739 foreach ($groupTree as $key => $group) {
2740 if ($key === 'info') {
2741 continue;
2742 }
2743
2744 foreach ($group['fields'] as $k => $customField) {
2745 $groupLabel = $group['title'];
2746 if (!empty($customField['customValue'])) {
2747 foreach ($customField['customValue'] as $customFieldValues) {
2748 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2749 }
2750 }
2751 }
2752 }
2753 $values['customGroup'] = $customGroup;
2754
2755 return $values;
2756 }
2757
2758 /**
2759 * Assign message variables to template but try to break the habit.
2760 *
2761 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2762 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2763 * multiple recurring payments for processors like IATS that use tokens.
2764 *
2765 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2766 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2767 * Note we send directly from this function in some cases because it is only partly refactored.
2768 *
2769 * Don't call this function directly as the signature will change.
2770 *
2771 * @param $values
2772 * @param $input
2773 * @param CRM_Core_SMARTY $template
2774 * @param bool $recur
2775 * @param bool $returnMessageText
2776 *
2777 * @return mixed
2778 */
2779 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2780 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2781 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2782 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2783 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2784 $values['useForMember'] = TRUE;
2785 }
2786 //assign honor information to receipt message
2787 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
2788
2789 if (isset($softRecord['soft_credit'])) {
2790 //if id of contribution page is present
2791 if (!empty($values['id'])) {
2792 $values['honor'] = array(
2793 'honor_profile_values' => array(),
2794 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2795 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2796 );
2797 $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
2798
2799 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2800 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2801 }
2802 else {
2803 //offline contribution
2804 $softCreditTypes = $softCredits = array();
2805 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2806 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2807 $softCredits[$key] = array(
2808 'Name' => $softCredit['contact_name'],
2809 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
2810 );
2811 }
2812 $template->assign('softCreditTypes', $softCreditTypes);
2813 $template->assign('softCredits', $softCredits);
2814 }
2815 }
2816
2817 $dao = new CRM_Contribute_DAO_ContributionProduct();
2818 $dao->contribution_id = $this->id;
2819 if ($dao->find(TRUE)) {
2820 $premiumId = $dao->product_id;
2821 $template->assign('option', $dao->product_option);
2822
2823 $productDAO = new CRM_Contribute_DAO_Product();
2824 $productDAO->id = $premiumId;
2825 $productDAO->find(TRUE);
2826 $template->assign('selectPremium', TRUE);
2827 $template->assign('product_name', $productDAO->name);
2828 $template->assign('price', $productDAO->price);
2829 $template->assign('sku', $productDAO->sku);
2830 }
2831 $template->assign('title', CRM_Utils_Array::value('title', $values));
2832 $values['amount'] = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
2833 if (!$values['amount'] && isset($this->total_amount)) {
2834 $values['amount'] = $this->total_amount;
2835 }
2836
2837 // add the new contribution values
2838 if (strtolower($this->_component) == 'contribute') {
2839 //PCP Info
2840 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2841 $softDAO->contribution_id = $this->id;
2842 if ($softDAO->find(TRUE)) {
2843 $template->assign('pcpBlock', TRUE);
2844 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2845 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2846 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2847
2848 //assign the pcp page title for email subject
2849 $pcpDAO = new CRM_PCP_DAO_PCP();
2850 $pcpDAO->id = $softDAO->pcp_id;
2851 if ($pcpDAO->find(TRUE)) {
2852 $template->assign('title', $pcpDAO->title);
2853 }
2854 }
2855 }
2856
2857 if ($this->financial_type_id) {
2858 $values['financial_type_id'] = $this->financial_type_id;
2859 }
2860
2861 $template->assign('trxn_id', $this->trxn_id);
2862 $template->assign('receive_date',
2863 CRM_Utils_Date::processDate($this->receive_date)
2864 );
2865 $values['receipt_date'] = (empty($this->receipt_date) ? NULL : $this->receipt_date);
2866 $template->assign('contributeMode', 'notify');
2867 $template->assign('action', $this->is_test ? 1024 : 1);
2868 $template->assign('receipt_text',
2869 CRM_Utils_Array::value('receipt_text',
2870 $values
2871 )
2872 );
2873 $template->assign('is_monetary', 1);
2874 $template->assign('is_recur', (bool) $recur);
2875 $template->assign('currency', $this->currency);
2876 $template->assign('address', CRM_Utils_Address::format($input));
2877 if (!empty($values['customGroup'])) {
2878 $template->assign('customGroup', $values['customGroup']);
2879 }
2880 if (!empty($values['softContributions'])) {
2881 $template->assign('softContributions', $values['softContributions']);
2882 }
2883 if ($this->_component == 'event') {
2884 $template->assign('title', $values['event']['title']);
2885 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2886 $viewRoles = array();
2887 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2888 $viewRoles[] = $participantRoles[$v];
2889 }
2890 $values['event']['participant_role'] = implode(', ', $viewRoles);
2891 $template->assign('event', $values['event']);
2892 $template->assign('participant', $values['participant']);
2893 $template->assign('location', $values['location']);
2894 $template->assign('customPre', $values['custom_pre_id']);
2895 $template->assign('customPost', $values['custom_post_id']);
2896
2897 $isTest = FALSE;
2898 if ($this->_relatedObjects['participant']->is_test) {
2899 $isTest = TRUE;
2900 }
2901
2902 $values['params'] = array();
2903 //to get email of primary participant.
2904 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2905 $primaryAmount[] = array(
2906 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
2907 'amount' => $this->_relatedObjects['participant']->fee_amount,
2908 );
2909 //build an array of cId/pId of participants
2910 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2911 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2912 //send receipt to additional participant if exists
2913 if (count($additionalIDs)) {
2914 $template->assign('isPrimary', 0);
2915 $template->assign('customProfile', NULL);
2916 //set additionalParticipant true
2917 $values['params']['additionalParticipant'] = TRUE;
2918 foreach ($additionalIDs as $pId => $cId) {
2919 $amount = array();
2920 //to change the status pending to completed
2921 $additional = new CRM_Event_DAO_Participant();
2922 $additional->id = $pId;
2923 $additional->contact_id = $cId;
2924 $additional->find(TRUE);
2925 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2926 $additional->status_id = 1;
2927 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2928 //if additional participant dont have email
2929 //use display name.
2930 if (!$additionalParticipantInfo) {
2931 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2932 }
2933 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2934 $primaryAmount[] = array(
2935 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
2936 'amount' => $additional->fee_amount,
2937 );
2938 $additional->save();
2939 $additional->free();
2940 $template->assign('amount', $amount);
2941 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2942 }
2943 }
2944
2945 //build an array of custom profile and assigning it to template
2946 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2947
2948 if (count($customProfile)) {
2949 $template->assign('customProfile', $customProfile);
2950 }
2951
2952 // for primary contact
2953 $values['params']['additionalParticipant'] = FALSE;
2954 $template->assign('isPrimary', 1);
2955 $template->assign('amount', $primaryAmount);
2956 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2957 if ($this->payment_instrument_id) {
2958 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2959 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2960 }
2961 // carry paylater, since we did not created billing,
2962 // so need to pull email from primary location, CRM-4395
2963 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2964 }
2965 return $template;
2966 }
2967
2968 /**
2969 * Check whether payment processor supports
2970 * cancellation of contribution subscription
2971 *
2972 * @param int $contributionId
2973 * Contribution id.
2974 *
2975 * @param bool $isNotCancelled
2976 *
2977 * @return bool
2978 */
2979 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2980 $cacheKeyString = "$contributionId";
2981 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2982
2983 static $supportsCancel = array();
2984
2985 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2986 $supportsCancel[$cacheKeyString] = FALSE;
2987 $isCancelled = FALSE;
2988
2989 if ($isNotCancelled) {
2990 $isCancelled = self::isSubscriptionCancelled($contributionId);
2991 }
2992
2993 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2994 if (!empty($paymentObject)) {
2995 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
2996 }
2997 }
2998 return $supportsCancel[$cacheKeyString];
2999 }
3000
3001 /**
3002 * Check whether subscription is already cancelled.
3003 *
3004 * @param int $contributionId
3005 * Contribution id.
3006 *
3007 * @return string
3008 * contribution status
3009 */
3010 public static function isSubscriptionCancelled($contributionId) {
3011 $sql = "
3012 SELECT cr.contribution_status_id
3013 FROM civicrm_contribution_recur cr
3014 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3015 WHERE con.id = %1 LIMIT 1";
3016 $params = array(1 => array($contributionId, 'Integer'));
3017 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
3018 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
3019 if ($status == 'Cancelled') {
3020 return TRUE;
3021 }
3022 return FALSE;
3023 }
3024
3025 /**
3026 * Create all financial accounts entry.
3027 *
3028 * @param array $params
3029 * Contribution object, line item array and params for trxn.
3030 *
3031 *
3032 * @param array $financialTrxnValues
3033 *
3034 * @return null|object
3035 */
3036 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3037 $skipRecords = $update = $return = $isRelatedId = FALSE;
3038
3039 $additionalParticipantId = array();
3040 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3041 $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']];
3042
3043 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
3044 $entityId = $params['participant_id'];
3045 $entityTable = 'civicrm_participant';
3046 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
3047 }
3048 elseif (!empty($params['membership_id'])) {
3049 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3050 // are created off one contribution should be handled elsewhere
3051 $entityId = $params['membership_id'];
3052 $entityTable = 'civicrm_membership';
3053 }
3054 else {
3055 $entityId = $params['contribution']->id;
3056 $entityTable = 'civicrm_contribution';
3057 }
3058
3059 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
3060 $isRelatedId = TRUE;
3061 }
3062
3063 $entityID[] = $entityId;
3064 if (!empty($additionalParticipantId)) {
3065 $entityID += $additionalParticipantId;
3066 }
3067 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3068 if (empty($params['prevContribution'])) {
3069 $entityID = NULL;
3070 }
3071 else {
3072 $update = TRUE;
3073 }
3074
3075 $statusId = $params['contribution']->contribution_status_id;
3076 // CRM-13964 partial payment
3077 if ($contributionStatus == 'Partially paid'
3078 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3079 ) {
3080 $partialAmtPay = $params['partial_amount_pay'];
3081 $partialAmtTotal = $params['partial_payment_total'];
3082
3083 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3084 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
3085 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
3086 $params['total_amount'] = $partialAmtPay;
3087
3088 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
3089 if (empty($balanceTrxnInfo['trxn_id'])) {
3090 // create new balance transaction record
3091 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3092 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
3093
3094 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3095 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3096 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
3097 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis');
3098 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
3099 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
3100 $balanceTrxnParams['currency'] = $params['contribution']->currency;
3101 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
3102 $balanceTrxnParams['status_id'] = $statusId;
3103 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3104 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
3105 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3106 ($statusId == array_search('Completed', $contributionStatuses) || $statusId == array_search('Partially paid', $contributionStatuses))
3107 ) {
3108 $balanceTrxnParams['is_payment'] = 1;
3109 }
3110 if (!empty($params['payment_processor'])) {
3111 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3112 }
3113 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
3114 }
3115 }
3116
3117 // build line item array if its not set in $params
3118 if (empty($params['line_item']) || $additionalParticipantId) {
3119 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3120 }
3121
3122 if ($contributionStatus != 'Failed' &&
3123 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later)
3124 ) {
3125 $skipRecords = TRUE;
3126 $pendingStatus = array(
3127 'Pending',
3128 'In Progress',
3129 );
3130 if (in_array($contributionStatus, $pendingStatus)) {
3131 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
3132 $params['financial_type_id'],
3133 'Accounts Receivable Account is'
3134 );
3135 }
3136 elseif (!empty($params['payment_processor'])) {
3137 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3138 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3139 'id' => $params['payment_processor'],
3140 'return' => 'payment_instrument_id',
3141 ));
3142 }
3143 elseif (!empty($params['payment_instrument_id'])) {
3144 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
3145 }
3146 else {
3147 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3148 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3149 $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);
3150 }
3151
3152 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
3153 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3154 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
3155 }
3156
3157 //build financial transaction params
3158 $trxnParams = array(
3159 'contribution_id' => $params['contribution']->id,
3160 'to_financial_account_id' => $params['to_financial_account_id'],
3161 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'),
3162 'total_amount' => $totalAmount,
3163 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
3164 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
3165 'currency' => $params['contribution']->currency,
3166 'trxn_id' => $params['contribution']->trxn_id,
3167 'status_id' => $statusId,
3168 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id),
3169 'check_number' => CRM_Utils_Array::value('check_number', $params),
3170 );
3171 if ($contributionStatus == 'Refunded' || $contributionStatus == 'Chargeback') {
3172 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis');
3173 if (isset($params['refund_trxn_id'])) {
3174 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3175 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3176 }
3177 }
3178 //CRM-16259, set is_payment flag for non pending status
3179 if (!in_array($contributionStatus, $pendingStatus)) {
3180 $trxnParams['is_payment'] = 1;
3181 }
3182 if (!empty($params['payment_processor'])) {
3183 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3184 }
3185
3186 if (isset($fromFinancialAccountId)) {
3187 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3188 }
3189
3190 // consider external values passed for recording transaction entry
3191 if (!empty($financialTrxnValues)) {
3192 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3193 }
3194
3195 $params['trxnParams'] = $trxnParams;
3196
3197 if (!empty($params['prevContribution'])) {
3198 $updated = FALSE;
3199 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
3200 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
3201 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
3202 if (!isset($params['trxnParams']['trxn_id'])) {
3203 // Actually I have no idea why we are overwriting any values from the previous contribution.
3204 // (filling makes sense to me). However, only protecting this value as I really really know we
3205 // don't want this one overwritten.
3206 // CRM-17751.
3207 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
3208 }
3209 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
3210
3211 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
3212 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
3213 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
3214 ) {
3215 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3216 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3217 }
3218
3219 //if financial type is changed
3220 if (!empty($params['financial_type_id']) &&
3221 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
3222 ) {
3223 $accountRelationship = 'Income Account is';
3224 if (!empty($params['revenue_recognition_date']) || $params['prevContribution']->revenue_recognition_date) {
3225 $accountRelationship = 'Deferred Revenue Account is';
3226 }
3227 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '$accountRelationship' "));
3228 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $relationTypeId);
3229 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
3230 if ($oldFinancialAccount != $newFinancialAccount) {
3231 $params['total_amount'] = 0;
3232 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
3233 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
3234 $params['prevContribution']->financial_type_id, $relationTypeId);
3235 }
3236 else {
3237 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
3238 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3239 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3240 }
3241 }
3242 self::updateFinancialAccounts($params, 'changeFinancialType');
3243 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3244 $params['financial_account_id'] = $newFinancialAccount;
3245 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3246 self::updateFinancialAccounts($params);
3247 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3248 $updated = TRUE;
3249 $params['deferred_financial_account_id'] = $newFinancialAccount;
3250 }
3251 }
3252
3253 //Update contribution status
3254 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
3255 if (!isset($params['refund_trxn_id'])) {
3256 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3257 // gets preference over another so I am only 'protecting' a very specific tested flow
3258 // and letting natural justice take care of the rest.
3259 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3260 }
3261 if (!empty($params['contribution_status_id']) &&
3262 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3263 ) {
3264 //Update Financial Records
3265 self::updateFinancialAccounts($params, 'changedStatus');
3266 $updated = TRUE;
3267 }
3268
3269 // change Payment Instrument for a Completed contribution
3270 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3271 // instrument is null and now new payment instrument is added along with the payment
3272 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3273 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
3274 if (array_key_exists('payment_instrument_id', $params)) {
3275 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3276 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
3277 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)
3278 ) {
3279 //check if status is changed from Pending to Completed
3280 // do not update payment instrument changes for Pending to Completed
3281 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
3282 in_array($params['prevContribution']->contribution_status_id, $pendingStatus))
3283 ) {
3284 // for all other statuses create new financial records
3285 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3286 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3287 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3288 $updated = TRUE;
3289 }
3290 }
3291 elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
3292 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
3293 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id
3294 ) {
3295 // for any other payment instrument changes create new financial records
3296 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3297 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3298 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3299 $updated = TRUE;
3300 }
3301 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
3302 $params['contribution']->check_number != $params['prevContribution']->check_number
3303 ) {
3304 // another special case when check number is changed, create new financial records
3305 // create financial trxn with negative amount
3306 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3307 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3308 // create financial trxn with positive amount
3309 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
3310 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3311 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3312 $updated = TRUE;
3313 }
3314 }
3315
3316 //if Change contribution amount
3317 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
3318 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
3319 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3320 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3321 if (isset($totalAmount) &&
3322 $totalAmount != $params['prevContribution']->total_amount
3323 ) {
3324 //Update Financial Records
3325 $params['trxnParams']['from_financial_account_id'] = NULL;
3326 self::updateFinancialAccounts($params, 'changedAmount');
3327 $updated = TRUE;
3328 }
3329
3330 if (!$updated) {
3331 // Looks like we might have a data correction update.
3332 // This would be a case where a transaction id has been entered but it is incorrect &
3333 // the person goes back in & fixes it, as opposed to a new transaction.
3334 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3335 // the data fix scenario.
3336 // CRM-17751.
3337 if (isset($params['refund_trxn_id'])) {
3338 $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']);
3339 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3340 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3341 }
3342 }
3343 }
3344 }
3345
3346 if (!$update) {
3347 // records finanical trxn and entity financial trxn
3348 // also make it available as return value
3349 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
3350 $params['entity_id'] = $financialTxn->id;
3351 }
3352 }
3353 // record line items and financial items
3354 if (empty($params['skipLineItem'])) {
3355 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
3356 }
3357
3358 // create batch entry if batch_id is passed and
3359 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3360 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3361 $entityParams = array(
3362 'batch_id' => $params['batch_id'],
3363 'entity_table' => 'civicrm_financial_trxn',
3364 'entity_id' => $financialTxn->id,
3365 );
3366 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
3367 }
3368
3369 // when a fee is charged
3370 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
3371 CRM_Core_BAO_FinancialTrxn::recordFees($params);
3372 }
3373
3374 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3375 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3376 ) {
3377 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3378 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
3379 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
3380 }
3381 unset($params['line_item']);
3382
3383 return $return;
3384 }
3385
3386 /**
3387 * Update all financial accounts entry.
3388 *
3389 * @param array $params
3390 * Contribution object, line item array and params for trxn.
3391 *
3392 * @param string $context
3393 * Update scenarios.
3394 *
3395 * @param null $skipTrxn
3396 *
3397 */
3398 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3399 $itemAmount = $trxnID = NULL;
3400 //get all the statuses
3401 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3402 $previousContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['prevContribution']->contribution_status_id, 'name');
3403 if (($previousContributionStatus == 'Pending'
3404 || $previousContributionStatus == 'In Progress')
3405 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
3406 && $context == 'changePaymentInstrument'
3407 ) {
3408 return;
3409 }
3410 if ((($previousContributionStatus == 'Partially paid'
3411 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
3412 || ($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later == TRUE
3413 && $params['contribution']->contribution_status_id == array_search('Partially paid', $contributionStatus)))
3414 && $context == 'changedStatus'
3415 ) {
3416 return;
3417 }
3418 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
3419 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
3420 }
3421 if ($context == 'changedStatus') {
3422 //get all the statuses
3423 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3424 $cancelledTaxAmount = 0;
3425 if ($previousContributionStatus == 'Completed'
3426 && (self::isContributionStatusNegative($params['contribution']->contribution_status_id))
3427 ) {
3428 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3429 $cancelledTaxAmount = CRM_Utils_Array::value('tax_amount', $params, '0.00');
3430 if (empty($params['contribution']->creditnote_id) || $params['contribution']->creditnote_id == "null") {
3431 $creditNoteId = self::createCreditNoteId();
3432 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId);
3433 }
3434 }
3435 elseif (($previousContributionStatus == 'Pending'
3436 && $params['prevContribution']->is_pay_later) || $previousContributionStatus == 'In Progress'
3437 ) {
3438 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
3439 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3440 $arAccountId = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeID, $relationTypeId);
3441
3442 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
3443 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3444 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3445 if (is_null($params['contribution']->creditnote_id) || $params['contribution']->creditnote_id == "null") {
3446 $creditNoteId = self::createCreditNoteId();
3447 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId);
3448 }
3449 }
3450 else {
3451 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3452 }
3453 }
3454 $itemAmount = $params['trxnParams']['total_amount'] + $cancelledTaxAmount;
3455 }
3456 elseif ($context == 'changePaymentInstrument') {
3457 if ($params['trxnParams']['total_amount'] < 0) {
3458 $deferredFinancialAccount = CRM_Utils_Array::value('deferred_financial_account_id', $params);
3459 if (empty($deferredFinancialAccount)) {
3460 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
3461 $deferredFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $relationTypeId);
3462 }
3463 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC', FALSE, NULL, $deferredFinancialAccount);
3464 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3465 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3466 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3467 }
3468 }
3469 else {
3470 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3471 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3472 }
3473 }
3474
3475 if ($context == 'changedStatus') {
3476 if (($previousContributionStatus == 'Pending'
3477 || $previousContributionStatus == 'In Progress')
3478 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
3479 ) {
3480 if (empty($params['line_item'])) {
3481 //CRM-15296
3482 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3483 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3484 // & this can be removed
3485 return;
3486 }
3487 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
3488 $params['entity_id'] = $trxn->id;
3489 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3490 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3491
3492 $entityParams = array(
3493 'entity_table' => 'civicrm_financial_item',
3494 'financial_trxn_id' => $trxn->id,
3495 );
3496 foreach ($params['line_item'] as $fieldId => $fields) {
3497 foreach ($fields as $fieldValueId => $fieldValues) {
3498 $fparams = array(
3499 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3500 2 => array($fieldValues['id'], 'Integer'),
3501 );
3502 CRM_Core_DAO::executeQuery($query, $fparams);
3503 $fparams = array(
3504 1 => array($fieldValues['id'], 'Integer'),
3505 );
3506 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
3507 while ($financialItem->fetch()) {
3508 $entityParams['entity_id'] = $financialItem->id;
3509 $entityParams['amount'] = $financialItem->amount;
3510 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
3511 }
3512 }
3513 }
3514 return;
3515 }
3516 }
3517
3518 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
3519 $params['entity_id'] = $trxn->id;
3520 if ($context != 'changePaymentInstrument') {
3521 $itemParams['entity_table'] = 'civicrm_line_item';
3522 $trxnIds['id'] = $params['entity_id'];
3523 foreach ($params['line_item'] as $fieldId => $fields) {
3524 foreach ($fields as $fieldValueId => $fieldValues) {
3525 $prevFinancialItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($fieldValues['id']);
3526 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
3527 if ($params['contribution']->receive_date) {
3528 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
3529 }
3530
3531 $financialAccount = self::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3532
3533 $currency = $params['prevContribution']->currency;
3534 if ($params['contribution']->currency) {
3535 $currency = $params['contribution']->currency;
3536 }
3537 $diff = 1;
3538 if ($context == 'changeFinancialType' || self::isContributionStatusNegative($params['contribution']->contribution_status_id)) {
3539 $diff = -1;
3540 }
3541 if (!empty($params['is_quick_config'])) {
3542 $amount = $itemAmount;
3543 if (!$amount) {
3544 $amount = $params['total_amount'];
3545 }
3546 }
3547 else {
3548 $amount = $diff * $fieldValues['line_total'];
3549 }
3550
3551 $itemParams = array(
3552 'transaction_date' => $receiveDate,
3553 'contact_id' => $params['prevContribution']->contact_id,
3554 'currency' => $currency,
3555 'amount' => $amount,
3556 'description' => $prevFinancialItem->description,
3557 'status_id' => $prevFinancialItem->status_id,
3558 'financial_account_id' => $financialAccount,
3559 'entity_table' => 'civicrm_line_item',
3560 'entity_id' => $fieldValues['id'],
3561 );
3562 $financialItem = CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3563 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $amount;
3564 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id;
3565
3566 if ($fieldValues['tax_amount']) {
3567 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
3568 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
3569 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3570 $itemParams['description'] = $taxTerm;
3571 if ($fieldValues['financial_type_id']) {
3572 $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']);
3573 }
3574 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3575 }
3576 }
3577 }
3578 }
3579 if ($context == 'changeFinancialType') {
3580 $params['skipLineItem'] = FALSE;
3581 foreach ($params['line_item'] as &$lineItems) {
3582 foreach ($lineItems as &$line) {
3583 $line['financial_type_id'] = $params['financial_type_id'];
3584 }
3585 }
3586 }
3587 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, $context);
3588 }
3589
3590 /**
3591 * Is this contribution status a reversal.
3592 *
3593 * If so we would expect to record a negative value in the financial_trxn table.
3594 *
3595 * @param int $status_id
3596 *
3597 * @return bool
3598 */
3599 public static function isContributionStatusNegative($status_id) {
3600 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3601 return in_array(CRM_Contribute_PseudoConstant::contributionStatus($status_id, 'name'), $reversalStatuses);
3602 }
3603
3604 /**
3605 * Check status validation on update of a contribution.
3606 *
3607 * @param array $values
3608 * Previous form values before submit.
3609 *
3610 * @param array $fields
3611 * The input form values.
3612 *
3613 * @param array $errors
3614 * List of errors.
3615 *
3616 * @return bool
3617 */
3618 public static function checkStatusValidation($values, &$fields, &$errors) {
3619 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
3620 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3621 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3622 return FALSE;
3623 }
3624 }
3625 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3626 $checkStatus = array(
3627 'Cancelled' => array('Completed', 'Refunded'),
3628 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3629 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3630 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3631 'Refunded' => array('Cancelled', 'Completed'),
3632 'Partially paid' => array('Completed'),
3633 );
3634
3635 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3636 CRM_Utils_Array::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3637 ) {
3638 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3639 1 => $contributionStatuses[$values['contribution_status_id']],
3640 2 => $contributionStatuses[$fields['contribution_status_id']],
3641 ));
3642 }
3643 }
3644
3645 /**
3646 * Delete contribution of contact.
3647 *
3648 * CRM-12155
3649 *
3650 * @param int $contactId
3651 * Contact id.
3652 *
3653 */
3654 public static function deleteContactContribution($contactId) {
3655 $contribution = new CRM_Contribute_DAO_Contribution();
3656 $contribution->contact_id = $contactId;
3657 $contribution->find();
3658 while ($contribution->fetch()) {
3659 self::deleteContribution($contribution->id);
3660 }
3661 }
3662
3663 /**
3664 * Get options for a given contribution field.
3665 * @see CRM_Core_DAO::buildOptions
3666 *
3667 * @param string $fieldName
3668 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3669 * @param array $props whatever is known about this dao object.
3670 *
3671 * @return array|bool
3672 */
3673 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3674 $className = __CLASS__;
3675 $params = array();
3676 switch ($fieldName) {
3677 // This field is not part of this object but the api supports it
3678 case 'payment_processor':
3679 $className = 'CRM_Contribute_BAO_ContributionPage';
3680 // Filter results by contribution page
3681 if (!empty($props['contribution_page_id'])) {
3682 $page = civicrm_api('contribution_page', 'getsingle', array(
3683 'version' => 3,
3684 'id' => ($props['contribution_page_id']),
3685 ));
3686 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3687 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3688 }
3689 break;
3690
3691 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3692 case 'honor_type_id':
3693 $className = 'CRM_Contribute_BAO_ContributionSoft';
3694 $fieldName = 'soft_credit_type_id';
3695 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3696 break;
3697 }
3698 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3699 }
3700
3701 /**
3702 * Validate financial type.
3703 *
3704 * CRM-13231
3705 *
3706 * @param int $financialTypeId
3707 * Financial Type id.
3708 *
3709 * @param string $relationName
3710 *
3711 * @return array|bool
3712 */
3713 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3714 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3715 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
3716
3717 if (!$financialAccount) {
3718 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
3719 }
3720 return FALSE;
3721 }
3722
3723
3724 /**
3725 * Function to record additional payment for partial and refund contributions.
3726 *
3727 * @param int $contributionId
3728 * is the invoice contribution id (got created after processing participant payment).
3729 * @param array $trxnsData
3730 * to take user provided input of transaction details.
3731 * @param string $paymentType
3732 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3733 * @param int $participantId
3734 *
3735 * @return null|object
3736 */
3737 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3738 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
3739 $getInfoOf['id'] = $contributionId;
3740 $defaults = array();
3741 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
3742 if (!$participantId) {
3743 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3744 }
3745
3746 if ($paymentType == 'owed') {
3747 // build params for recording financial trxn entry
3748 $params['contribution'] = $contributionDAO;
3749 $params = array_merge($defaults, $params);
3750 $params['skipLineItem'] = TRUE;
3751 $params['partial_payment_total'] = $contributionDAO->total_amount;
3752 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3753 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3754 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
3755
3756 // record the entry
3757 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3758 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3759 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3760
3761 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
3762 if (!empty($trxnId)) {
3763 $trxnId = $trxnId['trxn_id'];
3764 }
3765 elseif (!empty($contributionDAO->payment_instrument_id)) {
3766 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
3767 }
3768 else {
3769 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3770 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3771 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3772 }
3773
3774 // update statuses
3775 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3776 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3777 FROM civicrm_financial_trxn ft
3778 LEFT JOIN civicrm_entity_financial_trxn eft
3779 ON (ft.id = eft.financial_trxn_id)
3780 WHERE eft.entity_table = 'civicrm_contribution'
3781 AND eft.entity_id = {$contributionId}
3782 AND ft.to_financial_account_id != {$toFinancialAccount}
3783 AND ft.status_id = {$statusId}
3784 ";
3785 $query = CRM_Core_DAO::executeQuery($sql);
3786 $query->fetch();
3787 $sumOfPayments = $query->sum_of_payments;
3788
3789 // update statuses
3790 if ($contributionDAO->total_amount == $sumOfPayments) {
3791 // update contribution status and
3792 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3793 $contributionDAO->contribution_status_id = $statusId;
3794 $contributionDAO->cancel_date = 'null';
3795 $contributionDAO->cancel_reason = NULL;
3796 $netAmount = !empty($trxnsData['net_amount']) ? NULL : $trxnsData['total_amount'];
3797 $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
3798 $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
3799 $contributionDAO->save();
3800
3801 //Change status of financial record too
3802 $financialTrxn->status_id = $statusId;
3803 $financialTrxn->save();
3804
3805 // note : not using the self::add method,
3806 // the reason because it performs 'status change' related code execution for financial records
3807 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3808 // are coded below i.e. just updating financial_item status to 'Paid'
3809
3810 if ($participantId) {
3811 // update participant status
3812 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3813 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3814 foreach ($ids as $val) {
3815 $participantUpdate['id'] = $val;
3816 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3817 CRM_Event_BAO_Participant::add($participantUpdate);
3818 }
3819 }
3820
3821 // update financial item statuses
3822 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3823 $paidStatus = array_search('Paid', $financialItemStatus);
3824
3825 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3826 $sqlFinancialItemUpdate = "
3827 UPDATE civicrm_financial_item fi
3828 LEFT JOIN civicrm_entity_financial_trxn eft
3829 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3830 SET status_id = {$paidStatus}
3831 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3832 ";
3833 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
3834 }
3835 }
3836 elseif ($paymentType == 'refund') {
3837 // build params for recording financial trxn entry
3838 $params['contribution'] = $contributionDAO;
3839 $params = array_merge($defaults, $params);
3840 $params['skipLineItem'] = TRUE;
3841 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3842 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3843
3844 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3845 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3846 $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
3847 // record the entry
3848 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3849
3850 // note : not using the self::add method,
3851 // the reason because it performs 'status change' related code execution for financial records
3852 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3853 // are coded below i.e. just updating financial_item status to 'Paid'
3854 if ($updateStatus) {
3855 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3856 }
3857 // add financial item entry
3858 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3859 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionDAO->id);
3860 if (!empty($lineItems)) {
3861 foreach ($lineItems as $lineItemId => $lineItemValue) {
3862 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount / $contributionDAO->total_amount);
3863 $addFinancialEntry = array(
3864 'transaction_date' => $financialTrxn->trxn_date,
3865 'contact_id' => $contributionDAO->contact_id,
3866 'amount' => round($paid, 2),
3867 'status_id' => array_search('Paid', $financialItemStatus),
3868 'entity_id' => $lineItemId,
3869 'entity_table' => 'civicrm_line_item',
3870 );
3871 $trxnIds['id'] = $financialTrxn->id;
3872 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
3873 }
3874 }
3875 if ($participantId) {
3876 // update participant status
3877 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3878 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3879 foreach ($ids as $val) {
3880 $participantUpdate['id'] = $val;
3881 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3882 CRM_Event_BAO_Participant::add($participantUpdate);
3883 }
3884 }
3885 }
3886
3887 // activity creation
3888 if (!empty($financialTrxn)) {
3889 if ($participantId) {
3890 $inputParams['id'] = $participantId;
3891 $values = array();
3892 $ids = array();
3893 $component = 'event';
3894 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
3895 $entityObj = $entityObj[$participantId];
3896 }
3897 $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment';
3898
3899 self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3900 }
3901 return $financialTrxn;
3902 }
3903
3904 /**
3905 * @param $entityObj
3906 * @param $trxnObj
3907 * @param $activityType
3908 * @param $component
3909 * @param int $contributionId
3910 *
3911 * @throws CRM_Core_Exception
3912 */
3913 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3914 if ($component == 'event') {
3915 $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
3916 $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
3917 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
3918 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3919 $targetCid = $entityObj->contact_id;
3920 // source record id would be the contribution id
3921 $srcRecId = $contributionId;
3922 }
3923
3924 // activity params
3925 $activityParams = array(
3926 'source_contact_id' => $targetCid,
3927 'source_record_id' => $srcRecId,
3928 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
3929 $activityType,
3930 'name'
3931 ),
3932 'subject' => $subject,
3933 'activity_date_time' => $date,
3934 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
3935 'Completed',
3936 'name'
3937 ),
3938 'skipRecentView' => TRUE,
3939 );
3940
3941 // create activity with target contacts
3942 $session = CRM_Core_Session::singleton();
3943 $id = $session->get('userID');
3944 if ($id) {
3945 $activityParams['source_contact_id'] = $id;
3946 $activityParams['target_contact_id'][] = $targetCid;
3947 }
3948 CRM_Activity_BAO_Activity::create($activityParams);
3949 }
3950
3951 /**
3952 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3953 *
3954 * @param int $id
3955 * @param $component
3956 * @param bool $getTrxnInfo
3957 * @param bool $usingLineTotal
3958 *
3959 * @return mixed
3960 */
3961 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3962 if ($component == 'event') {
3963 $entity = 'participant';
3964 $entityTable = 'civicrm_participant';
3965 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3966
3967 if (!$contributionId) {
3968 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3969 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3970 $id = $primaryParticipantId;
3971 }
3972 if (!$contributionId) {
3973 return;
3974 }
3975 }
3976 }
3977 else {
3978 $contributionId = $id;
3979 $entity = 'contribution';
3980 $entityTable = 'civicrm_contribution';
3981 }
3982
3983 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
3984 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
3985 if (!$baseTrxnId) {
3986 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3987 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3988 }
3989 if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) {
3990 // for additional participants
3991 if ($entityTable == 'civicrm_participant') {
3992 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3993 $total = 0;
3994 foreach ($ids as $val) {
3995 $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable);
3996 }
3997 }
3998 else {
3999 $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
4000 }
4001 }
4002 else {
4003 $baseTrxnId = $total['trxn_id'];
4004 $total = $total['total_amount'];
4005 }
4006
4007 $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
4008 $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
4009
4010 $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
4011 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4012 $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
4013
4014 if ($paymentBalance == 0 && $contributionIsPayLater) {
4015 $paymentBalance = $total;
4016 }
4017
4018 $info['total'] = $total;
4019 $info['paid'] = $total - $paymentBalance;
4020 $info['balance'] = $paymentBalance;
4021 $info['id'] = $id;
4022 $info['component'] = $component;
4023 $info['payLater'] = $contributionIsPayLater;
4024 $rows = array();
4025 if ($getTrxnInfo && $baseTrxnId) {
4026 $arRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4027 $arAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $arRelationTypeId);
4028
4029 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4030 $sql = "
4031 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4032 ft.total_amount,
4033 ft.payment_instrument_id,
4034 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency
4035
4036 FROM civicrm_contribution con
4037 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4038 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4039 AND ft.to_financial_account_id != %2
4040 INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4041 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4042 INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4043
4044 WHERE con.id = %1 AND ft.to_financial_account_id <> %3
4045 GROUP BY ft.id";
4046
4047 $queryParams = array(
4048 1 => array($contributionId, 'Integer'),
4049 2 => array($feeFinancialAccount, 'Integer'),
4050 3 => array($arAccount, 'Integer'),
4051 );
4052 $resultDAO = CRM_Core_DAO::executeQuery($sql, $queryParams);
4053
4054 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
4055
4056 while ($resultDAO->fetch()) {
4057 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
4058 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
4059 $val = array(
4060 'total_amount' => $resultDAO->total_amount,
4061 'financial_type' => $resultDAO->financial_account,
4062 'payment_instrument' => $paidByLabel,
4063 'receive_date' => $resultDAO->trxn_date,
4064 'trxn_id' => $resultDAO->trxn_id,
4065 'status' => $statuses[$resultDAO->status_id],
4066 'currency' => $resultDAO->currency,
4067 );
4068 if ($paidByName == 'Check') {
4069 $val['check_number'] = $resultDAO->check_number;
4070 }
4071 $rows[] = $val;
4072 }
4073 $info['transaction'] = $rows;
4074 }
4075 return $info;
4076 }
4077
4078 /**
4079 * Get financial account id has 'Sales Tax Account is'
4080 * account relationship with financial type
4081 *
4082 * @param int $financialTypeId
4083 *
4084 * @return FinancialAccountId
4085 */
4086 public static function getFinancialAccountId($financialTypeId) {
4087 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4088 $searchParams = array(
4089 'entity_table' => 'civicrm_financial_type',
4090 'entity_id' => $financialTypeId,
4091 'account_relationship' => $accountRel,
4092 );
4093 $result = array();
4094 CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
4095
4096 return CRM_Utils_Array::value('financial_account_id', $result);
4097 }
4098
4099 /**
4100 * Check tax amount.
4101 *
4102 * @param array $params
4103 * @param bool $isLineItem
4104 *
4105 * @return mixed
4106 */
4107 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4108 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
4109
4110 // Update contribution.
4111 if (!empty($params['id'])) {
4112 $id = $params['id'];
4113 $values = $ids = array();
4114 $contrbutionParams = array('id' => $id);
4115 $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids);
4116
4117 // To assign pervious finantial type on update of contribution
4118 if (!isset($params['financial_type_id'])) {
4119 $params['financial_type_id'] = $prevContributionValue->financial_type_id;
4120 }
4121 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
4122 // Assisn tax Amount on update of contrbution
4123 if (!empty($prevContributionValue->tax_amount)) {
4124 $params['tax_amount'] = 'null';
4125 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
4126 foreach ($params['line_item'] as $setID => $priceField) {
4127 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4128 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4129 }
4130 }
4131 }
4132 }
4133 }
4134
4135 // New Contrbution and update of contribution with tax rate financial type
4136 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4137 empty($params['skipLineItem']) && !$isLineItem
4138 ) {
4139 $taxRateParams = $taxRates[$params['financial_type_id']];
4140 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams);
4141 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4142
4143 // Get Line Item on update of contribution
4144 if (isset($params['id'])) {
4145 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
4146 }
4147 else {
4148 CRM_Price_BAO_LineItem::getLineItemArray($params);
4149 }
4150 foreach ($params['line_item'] as $setID => $priceField) {
4151 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4152 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4153 }
4154 }
4155 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount'];
4156 }
4157 elseif (isset($params['api.line_item.create'])) {
4158 // Update total amount of contribution using lineItem
4159 $taxAmountArray = array();
4160 foreach ($params['api.line_item.create'] as $key => $value) {
4161 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4162 $taxRate = $taxRates[$value['financial_type_id']];
4163 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
4164 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4165 }
4166 }
4167 $params['tax_amount'] = array_sum($taxAmountArray);
4168 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
4169 }
4170 else {
4171 // update line item of contrbution
4172 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4173 $taxRate = $taxRates[$params['financial_type_id']];
4174 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate);
4175 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4176 }
4177 }
4178 return $params;
4179 }
4180
4181 /**
4182 * Check financial type validation on update of a contribution.
4183 *
4184 * @param Integer $financialTypeId
4185 * Value of latest Financial Type.
4186 *
4187 * @param Integer $contributionId
4188 * Contribution Id.
4189 *
4190 * @param array $errors
4191 * List of errors.
4192 *
4193 * @return bool
4194 */
4195 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4196 if (!empty($financialTypeId)) {
4197 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4198 if ($oldFinancialTypeId == $financialTypeId) {
4199 return FALSE;
4200 }
4201 }
4202 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4203 $params = array(
4204 '1' => array($contributionId, 'Integer'),
4205 );
4206 $result = CRM_Core_DAO::executeQuery($sql, $params);
4207 if ($result->N > 1) {
4208 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
4209 }
4210 }
4211
4212 /**
4213 * Update related pledge payment payments.
4214 *
4215 * This function has been refactored out of the back office contribution form and may
4216 * still overlap with other functions.
4217 *
4218 * @param string $action
4219 * @param int $pledgePaymentID
4220 * @param int $contributionID
4221 * @param bool $adjustTotalAmount
4222 * @param float $total_amount
4223 * @param float $original_total_amount
4224 * @param int $contribution_status_id
4225 * @param int $original_contribution_status_id
4226 */
4227 public static function updateRelatedPledge(
4228 $action,
4229 $pledgePaymentID,
4230 $contributionID,
4231 $adjustTotalAmount,
4232 $total_amount,
4233 $original_total_amount,
4234 $contribution_status_id,
4235 $original_contribution_status_id
4236 ) {
4237 if (!$pledgePaymentID && $action & CRM_Core_Action::ADD && !$contributionID) {
4238 return;
4239 }
4240
4241 if ($pledgePaymentID) {
4242 //store contribution id in payment record.
4243 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4244 }
4245 else {
4246 $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4247 $contributionID,
4248 'id',
4249 'contribution_id'
4250 );
4251 }
4252
4253 if (!$pledgePaymentID) {
4254 return;
4255 }
4256 $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4257 $contributionID,
4258 'pledge_id',
4259 'contribution_id'
4260 );
4261
4262 $updatePledgePaymentStatus = FALSE;
4263
4264 // If either the status or the amount has changed we update the pledge status.
4265 if ($action & CRM_Core_Action::ADD) {
4266 $updatePledgePaymentStatus = TRUE;
4267 }
4268 elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) ||
4269 ($original_total_amount != $total_amount))
4270 ) {
4271 $updatePledgePaymentStatus = TRUE;
4272 }
4273
4274 if ($updatePledgePaymentStatus) {
4275 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID,
4276 array($pledgePaymentID),
4277 $contribution_status_id,
4278 NULL,
4279 $total_amount,
4280 $adjustTotalAmount
4281 );
4282 }
4283 }
4284
4285 /**
4286 * Compute the stats values
4287 *
4288 * @param $stat either 'mode' or 'median'
4289 * @param $sql
4290 * @param $alias of civicrm_contribution
4291 */
4292 public static function computeStats($stat, $sql, $alias = NULL) {
4293 $mode = $median = array();
4294 switch ($stat) {
4295 case 'mode':
4296 $modeDAO = CRM_Core_DAO::executeQuery($sql);
4297 while ($modeDAO->fetch()) {
4298 if ($modeDAO->civicrm_contribution_total_amount_count > 1) {
4299 $mode[] = CRM_Utils_Money::format($modeDAO->amount, $modeDAO->currency);
4300 }
4301 else {
4302 $mode[] = 'N/A';
4303 }
4304 }
4305 return $mode;
4306
4307 case 'median':
4308 $currencies = CRM_Core_OptionGroup::values('currencies_enabled');
4309 foreach ($currencies as $currency => $val) {
4310 $midValue = 0;
4311 $where = "AND {$alias}.currency = '{$currency}'";
4312 $rowCount = CRM_Core_DAO::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4313
4314 $even = FALSE;
4315 $offset = 1;
4316 $medianRow = floor($rowCount / 2);
4317 if ($rowCount % 2 == 0 && !empty($medianRow)) {
4318 $even = TRUE;
4319 $offset++;
4320 $medianRow--;
4321 }
4322
4323 $medianValue = "SELECT {$alias}.total_amount as median
4324 {$sql} {$where}
4325 ORDER BY median LIMIT {$medianRow},{$offset}";
4326 $medianValDAO = CRM_Core_DAO::executeQuery($medianValue);
4327 while ($medianValDAO->fetch()) {
4328 if ($even) {
4329 $midValue = $midValue + $medianValDAO->median;
4330 }
4331 else {
4332 $median[] = CRM_Utils_Money::format($medianValDAO->median, $currency);
4333 }
4334 }
4335 if ($even) {
4336 $midValue = $midValue / 2;
4337 $median[] = CRM_Utils_Money::format($midValue, $currency);
4338 }
4339 }
4340 return $median;
4341
4342 default:
4343 return;
4344 }
4345 }
4346
4347 /**
4348 * Is there only one line item attached to the contribution.
4349 *
4350 * @param int $id
4351 * Contribution ID.
4352 *
4353 * @return bool
4354 * @throws \CiviCRM_API3_Exception
4355 */
4356 public static function isSingleLineItem($id) {
4357 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4358 return ($lineItemCount == 1);
4359 }
4360
4361 /**
4362 * Complete an order.
4363 *
4364 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4365 *
4366 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4367 *
4368 * Moving it out of the BaseIPN class is just the first step.
4369 *
4370 * @param array $input
4371 * @param array $ids
4372 * @param array $objects
4373 * @param CRM_Core_Transaction $transaction
4374 * @param int $recur
4375 * @param CRM_Contribute_BAO_Contribution $contribution
4376 * @param bool $isRecurring
4377 * Duplication of param needs review. Only used by AuthorizeNetIPN
4378 * @param int $isFirstOrLastRecurringPayment
4379 * Deprecated param only used by AuthorizeNetIPN.
4380 */
4381 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4382 $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
4383 // The previous details are used when calculating line items so keep it before any code that 'does something'
4384 if (!empty($contribution->id)) {
4385 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id),
4386 CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
4387 }
4388 $inputContributionWhiteList = array(
4389 'fee_amount',
4390 'net_amount',
4391 'trxn_id',
4392 'check_number',
4393 'payment_instrument_id',
4394 'is_test',
4395 'campaign_id',
4396 'receive_date',
4397 'receipt_date',
4398 'contribution_status_id',
4399 );
4400 if (self::isSingleLineItem($primaryContributionID)) {
4401 $inputContributionWhiteList[] = 'financial_type_id';
4402 }
4403
4404 $participant = CRM_Utils_Array::value('participant', $objects);
4405 $memberships = CRM_Utils_Array::value('membership', $objects);
4406 $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
4407 $recurringContributionID = (empty($recurContrib->id)) ? NULL : $recurContrib->id;
4408 $event = CRM_Utils_Array::value('event', $objects);
4409
4410 $paymentProcessorId = '';
4411 if (isset($objects['paymentProcessor'])) {
4412 if (is_array($objects['paymentProcessor'])) {
4413 $paymentProcessorId = $objects['paymentProcessor']['id'];
4414 }
4415 else {
4416 $paymentProcessorId = $objects['paymentProcessor']->id;
4417 }
4418 }
4419
4420 $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4421
4422 $contributionParams = array_merge(array(
4423 'contribution_status_id' => $completedContributionStatusID,
4424 'source' => self::getRecurringContributionDescription($contribution, $event),
4425 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4426 ));
4427 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4428
4429 if ($recurringContributionID) {
4430 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4431 }
4432 $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
4433
4434 if (empty($contributionParams['receive_date']) && $changeDate) {
4435 $contributionParams['receive_date'] = $changeDate;
4436 }
4437
4438 self::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4439 $contributionParams['financial_type_id'] = $contribution->financial_type_id;
4440
4441 if (is_numeric($memberships)) {
4442 $memberships = array($objects['membership']);
4443 }
4444
4445 $values = array();
4446 if (isset($input['is_email_receipt'])) {
4447 $values['is_email_receipt'] = $input['is_email_receipt'];
4448 }
4449
4450 if ($input['component'] == 'contribute') {
4451 if ($contribution->contribution_page_id) {
4452 // Figure out what we gain from this.
4453 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
4454 }
4455 elseif ($recurContrib && $recurringContributionID) {
4456 $values['amount'] = $recurContrib->amount;
4457 $values['financial_type_id'] = $objects['contributionType']->id;
4458 $values['title'] = $source = ts('Offline Recurring Contribution');
4459 }
4460
4461 if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
4462 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4463 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4464 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
4465 }
4466
4467 if (!empty($memberships)) {
4468 foreach ($memberships as $membershipTypeIdKey => $membership) {
4469 if ($membership) {
4470 $membershipParams = array(
4471 'id' => $membership->id,
4472 'contact_id' => $membership->contact_id,
4473 'is_test' => $membership->is_test,
4474 'membership_type_id' => $membership->membership_type_id,
4475 );
4476
4477 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'],
4478 $membershipParams['membership_type_id'],
4479 $membershipParams['is_test'],
4480 $membershipParams['id']
4481 );
4482
4483 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4484 // this picks up membership type changes during renewals
4485 $sql = "
4486 SELECT membership_type_id
4487 FROM civicrm_membership_log
4488 WHERE membership_id={$membershipParams['id']}
4489 ORDER BY id DESC
4490 LIMIT 1;";
4491 $dao = CRM_Core_DAO::executeQuery($sql);
4492 if ($dao->fetch()) {
4493 if (!empty($dao->membership_type_id)) {
4494 $membershipParams['membership_type_id'] = $dao->membership_type_id;
4495 }
4496 }
4497 $dao->free();
4498
4499 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4500 $membershipParams['membership_type_id'],
4501 $primaryContributionID
4502 );
4503 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4504 if ($currentMembership) {
4505 /*
4506 * Fixed FOR CRM-4433
4507 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4508 * when Contribution mode is notify and membership is for renewal )
4509 */
4510 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4511
4512 // @todo - we should pass membership_type_id instead of null here but not
4513 // adding as not sure of testing
4514 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'],
4515 $changeDate, NULL, $membershipParams['num_terms']
4516 );
4517
4518 $dates['join_date'] = $currentMembership['join_date'];
4519 }
4520
4521 //get the status for membership.
4522 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
4523 $dates['end_date'],
4524 $dates['join_date'],
4525 'today',
4526 TRUE,
4527 $membershipParams['membership_type_id'],
4528 $membershipParams
4529 );
4530
4531 $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
4532 //we might be renewing membership,
4533 //so make status override false.
4534 $membershipParams['is_override'] = FALSE;
4535 //CRM-17723 - reset static $relatedContactIds array()
4536 $var = TRUE;
4537 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
4538 civicrm_api3('Membership', 'create', $membershipParams);
4539 }
4540 }
4541 }
4542 }
4543 else {
4544 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4545 if ($event->is_email_confirm) {
4546 // @todo this should be set by the function that sends the mail after sending.
4547 $contributionParams['receipt_date'] = $changeDate;
4548 }
4549 $participantParams['id'] = $participant->id;
4550 $participantParams['status_id'] = 'Registered';
4551 civicrm_api3('Participant', 'create', $participantParams);
4552 }
4553 }
4554
4555 $contributionParams['id'] = $contribution->id;
4556
4557 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4558
4559 // Add new soft credit against current $contribution.
4560 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
4561 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
4562 }
4563
4564 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4565 'labelColumn' => 'name',
4566 'flip' => 1,
4567 ));
4568 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
4569 $input['payment_processor'] = $paymentProcessorId;
4570 }
4571
4572 if (!empty($contribution->_relatedObjects['participant'])) {
4573 $input['contribution_mode'] = 'participant';
4574 $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
4575 }
4576 elseif (!empty($contribution->_relatedObjects['membership'])) {
4577 $input['contribution_mode'] = 'membership';
4578 $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
4579 $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $input);
4580 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
4581 }
4582
4583 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
4584 $transaction->commit();
4585
4586 CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution->id, $recurringContributionID,
4587 $contributionParams['contribution_status_id'], $input['amount']);
4588
4589 // create an activity record
4590 if ($input['component'] == 'contribute') {
4591 //CRM-4027
4592 $targetContactID = NULL;
4593 if (!empty($ids['related_contact'])) {
4594 $targetContactID = $contribution->contact_id;
4595 $contribution->contact_id = $ids['related_contact'];
4596 }
4597 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
4598 // event
4599 }
4600 else {
4601 CRM_Activity_BAO_Activity::addActivity($participant);
4602 }
4603
4604 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4605 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4606 if (!array_key_exists('is_email_receipt', $values) ||
4607 $values['is_email_receipt'] == 1
4608 ) {
4609 civicrm_api3('Contribution', 'sendconfirmation', array(
4610 'id' => $contribution->id,
4611 'payment_processor_id' => $paymentProcessorId,
4612 ));
4613 CRM_Core_Error::debug_log_message("Receipt sent");
4614 }
4615
4616 CRM_Core_Error::debug_log_message("Success: Database updated");
4617 if ($isRecurring) {
4618 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
4619 $isFirstOrLastRecurringPayment);
4620 }
4621 return $contributionResult;
4622 }
4623
4624 /**
4625 * Send receipt from contribution.
4626 *
4627 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4628 *
4629 * Note that the compose message part has been moved to contribution
4630 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4631 *
4632 * @param array $input
4633 * Incoming data from Payment processor.
4634 * @param array $ids
4635 * Related object IDs.
4636 * @param int $contributionID
4637 * @param array $values
4638 * Values related to objects that have already been loaded.
4639 * @param bool $recur
4640 * Is it part of a recurring contribution.
4641 * @param bool $returnMessageText
4642 * Should text be returned instead of sent. This.
4643 * is because the function is also used to generate pdfs
4644 *
4645 * @return array
4646 * @throws \CRM_Core_Exception
4647 * @throws \CiviCRM_API3_Exception
4648 */
4649 public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE,
4650 $returnMessageText = FALSE) {
4651 $input['is_recur'] = $recur;
4652
4653 $contribution = new CRM_Contribute_BAO_Contribution();
4654 $contribution->id = $contributionID;
4655 if (!$contribution->find(TRUE)) {
4656 throw new CRM_Core_Exception('Contribution does not exist');
4657 }
4658 $contribution->loadRelatedObjects($input, $ids, TRUE);
4659 // set receipt from e-mail and name in value
4660 if (!$returnMessageText) {
4661 $session = CRM_Core_Session::singleton();
4662 $userID = $session->get('userID');
4663 if (!empty($userID)) {
4664 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
4665 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $input, $userEmail);
4666 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $input, $userName);
4667 }
4668 }
4669
4670 $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4671 // Contribution ID should really always be set. But ?
4672 if (!$returnMessageText && (!isset($input['receipt_update']) || $input['receipt_update']) && empty($contribution->receipt_date)) {
4673 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id));
4674 }
4675 return $return;
4676 }
4677
4678 /**
4679 * Generate credit note id with next avaible number
4680 *
4681 * @return string
4682 * Credit Note Id.
4683 */
4684 public static function createCreditNoteId() {
4685 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
4686
4687 $creditNoteNum = CRM_Core_DAO::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4688 $creditNoteId = NULL;
4689
4690 do {
4691 $creditNoteNum++;
4692 $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4693 $result = civicrm_api3('Contribution', 'getcount', array(
4694 'sequential' => 1,
4695 'creditnote_id' => $creditNoteId,
4696 ));
4697 } while ($result > 0);
4698
4699 return $creditNoteId;
4700 }
4701
4702 /**
4703 * Load related memberships.
4704 *
4705 * Note that in theory it should be possible to retrieve these from the line_item table
4706 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4707 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4708 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4709 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4710 *
4711 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4712 *
4713 * @param array $ids
4714 *
4715 * @throws Exception
4716 */
4717 public function loadRelatedMembershipObjects(&$ids) {
4718 $query = "
4719 SELECT membership_id
4720 FROM civicrm_membership_payment
4721 WHERE contribution_id = %1 ";
4722 $params = array(1 => array($this->id, 'Integer'));
4723
4724 $dao = CRM_Core_DAO::executeQuery($query, $params);
4725 while ($dao->fetch()) {
4726 if ($dao->membership_id) {
4727 if (!is_array($ids['membership'])) {
4728 $ids['membership'] = array();
4729 }
4730 $ids['membership'][] = $dao->membership_id;
4731 }
4732 }
4733
4734 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4735 foreach ($ids['membership'] as $id) {
4736 if (!empty($id)) {
4737 $membership = new CRM_Member_BAO_Membership();
4738 $membership->id = $id;
4739 if (!$membership->find(TRUE)) {
4740 throw new Exception("Could not find membership record: $id");
4741 }
4742 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
4743 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
4744 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
4745 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
4746 $membership->free();
4747 }
4748 }
4749 }
4750 }
4751
4752 /**
4753 * This function is used to record partial payments for contribution
4754 *
4755 * @param array $contribution
4756 *
4757 * @param array $params
4758 *
4759 * @return object
4760 */
4761 public static function recordPartialPayment($contribution, $params) {
4762 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
4763 $pendingStatus = array(
4764 array_search('Pending', $contributionStatuses),
4765 array_search('In Progress', $contributionStatuses),
4766 );
4767 $statusId = array_search('Completed', $contributionStatuses);
4768 if (in_array(CRM_Utils_Array::value('contribution_status_id', $contribution), $pendingStatus)) {
4769 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4770 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4771 }
4772 elseif (!empty($params['payment_processor'])) {
4773 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4774 }
4775 elseif (!empty($params['payment_instrument_id'])) {
4776 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4777 }
4778 else {
4779 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4780 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4781 $balanceTrxnParams['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);
4782 }
4783 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4784 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4785 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4786 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4787 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4788 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ? $params['contribution_receive_date'] : date('YmdHis');
4789 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
4790 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('total_amount', $params);
4791 $balanceTrxnParams['currency'] = $contribution['currency'];
4792 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array::value('contribution_trxn_id', $params, NULL);
4793 $balanceTrxnParams['status_id'] = $statusId;
4794 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4795 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
4796 if ($fromFinancialAccountId != NULL &&
4797 ($statusId == array_search('Completed', $contributionStatuses) || $statusId == array_search('Partially paid', $contributionStatuses))
4798 ) {
4799 $balanceTrxnParams['is_payment'] = 1;
4800 }
4801 if (!empty($params['payment_processor'])) {
4802 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4803 }
4804 return CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
4805 }
4806
4807 /**
4808 * Get the description (source field) for the recurring contribution.
4809 *
4810 * @param CRM_Contribute_BAO_Contribution $contribution
4811 * @param CRM_Event_DAO_Event|null $event
4812 *
4813 * @return array
4814 * @throws \CiviCRM_API3_Exception
4815 */
4816 protected static function getRecurringContributionDescription($contribution, $event) {
4817 if (!empty($contribution->source)) {
4818 return $contribution->source;
4819 }
4820 elseif (!empty($contribution->contribution_page_id)) {
4821 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4822 'id' => $contribution->contribution_page_id,
4823 'return' => 'title',
4824 ));
4825 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4826 }
4827 elseif ($event) {
4828 return ts('Online Event Registration') . ': ' . $event->title;
4829 }
4830 elseif (!empty($contribution->contribution_recur_id)) {
4831 return 'recurring contribution';
4832 }
4833 return '';
4834 }
4835
4836 /**
4837 * Function to add payments for contribution
4838 * for Partially Paid status
4839 *
4840 * @param array $lineItems
4841 * @param array $contributions
4842 * @param array $contributionStatusId
4843 *
4844 */
4845 public static function addPayments($lineItems, $contributions, $contributionStatusId = NULL) {
4846 // get financial trxn which is a payment
4847 $ftSql = "SELECT ft.id, ft.total_amount
4848 FROM civicrm_financial_trxn ft
4849 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4850 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4851 $sql = "SELECT fi.id, li.price_field_value_id
4852 FROM civicrm_financial_item fi
4853 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id
4854 WHERE li.contribution_id = %1";
4855 $contributionStatus = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4856 'labelColumn' => 'name',
4857 ));
4858 foreach ($contributions as $k => $contribution) {
4859 if (!($contributionStatus[$contribution->contribution_status_id] == 'Partially paid'
4860 || CRM_Utils_Array::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4861 ) {
4862 continue;
4863 }
4864 $ftDao = CRM_Core_DAO::executeQuery($ftSql, array(1 => array($contribution->id, 'Integer')));
4865 $ftDao->fetch();
4866 $trxnAmount = $ftDao->total_amount;
4867 $ftId = $ftDao->id;
4868
4869 // get financial item
4870 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($contribution->id, 'Integer')));
4871 while ($dao->fetch()) {
4872 $ftIds[$dao->price_field_value_id] = $dao->id;
4873 }
4874
4875 $params = array(
4876 'entity_table' => 'civicrm_financial_item',
4877 'financial_trxn_id' => $ftId,
4878 );
4879 foreach ($lineItems as $key => $value) {
4880 if ($value['qty'] == 0) {
4881 continue;
4882 }
4883 $paid = $value['line_total'] * ($trxnAmount / $contribution->total_amount);
4884 // Record Entity Financial Trxn
4885 $params['amount'] = round($paid, 2);
4886 $params['entity_id'] = $ftIds[$value['price_field_value_id']];
4887
4888 civicrm_api3('EntityFinancialTrxn', 'create', $params);
4889 }
4890 }
4891 }
4892
4893 /**
4894 * Function use to store line item proportionaly in
4895 * in entity financial trxn table
4896 *
4897 * @param array $params
4898 * array of contribution params.
4899 * @param object $trxn
4900 * CRM_Financial_DAO_FinancialTrxn object
4901 * @param array $contribution
4902 *
4903 */
4904 public static function assignProportionalLineItems($params, $trxn, $contribution) {
4905 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution_id']);
4906 if (!empty($lineItems)) {
4907 // get financial item
4908 $sql = "SELECT fi.id, li.price_field_value_id
4909 FROM civicrm_financial_item fi
4910 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4911 WHERE li.contribution_id = %1";
4912 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($params['contribution_id'], 'Integer')));
4913 while ($dao->fetch()) {
4914 $ftIds[$dao->price_field_value_id] = $dao->id;
4915 }
4916 $eftParams = array(
4917 'entity_table' => 'civicrm_financial_item',
4918 'financial_trxn_id' => $trxn->id,
4919 );
4920 foreach ($lineItems as $key => $value) {
4921 $paid = $value['line_total'] * ($params['total_amount'] / $contribution['total_amount']);
4922 // Record Entity Financial Trxn
4923 $eftParams['amount'] = round($paid, 2);
4924 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4925
4926 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4927 }
4928 }
4929 }
4930
4931 /**
4932 * Function to check line items
4933 *
4934 * @param array $params
4935 * array of order params.
4936 *
4937 */
4938 public static function checkLineItems(&$params) {
4939 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
4940 $lineItemAmount = 0;
4941 foreach ($params['line_items'] as &$lineItems) {
4942 foreach ($lineItems['line_item'] as &$item) {
4943 if (empty($item['financial_type_id'])) {
4944 $item['financial_type_id'] = $params['financial_type_id'];
4945 }
4946 $lineItemAmount += $item['line_total'];
4947 }
4948 }
4949 if (!isset($totalAmount)) {
4950 $params['total_amount'] = $lineItemAmount;
4951 }
4952 elseif ($totalAmount != $lineItemAmount) {
4953 throw new API_Exception("Line item total doesn't match with total amount.");
4954 }
4955 }
4956
4957 /**
4958 * Get the financial account for the item associated with the new transaction.
4959 *
4960 * @param array $params
4961 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
4962 *
4963 * @return int
4964 */
4965 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
4966
4967 if (!empty($params['financial_account_id'])) {
4968 return $params['financial_account_id'];
4969 }
4970 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['contribution_status_id'], 'name');
4971 $preferredAccountsRelationships = array(
4972 'Refunded' => 'Credit/Contra Revenue Account is',
4973 'Chargeback' => 'Chargeback Account is',
4974 );
4975 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4976 $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
4977 return CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
4978 $financialTypeID,
4979 $preferredAccountsRelationships[$contributionStatus]
4980 );
4981 }
4982 return $prevFinancialItem->financial_account_id;
4983 }
4984
4985 /**
4986 * ContributionPage values were being imposed onto values.
4987 *
4988 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4989 * REALLY didn't want superimposed. The rest are left there in their overkill out
4990 * of cautiousness.
4991 *
4992 * The rationale for making this explicit is that it was a case of carefully set values being
4993 * seemingly randonly overwritten without much care. In general I think array randomly setting
4994 * variables en mass is risky.
4995 *
4996 * @param array $values
4997 *
4998 * @return array
4999 */
5000 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5001 $contributionPageValues = array();
5002 CRM_Contribute_BAO_ContributionPage::setValues(
5003 $this->contribution_page_id,
5004 $contributionPageValues
5005 );
5006 $valuesToCopy = array(
5007 // These are the values that I believe to be useful.
5008 'title',
5009 'is_email_receipt',
5010 'pay_later_receipt',
5011 'pay_later_text',
5012 'receipt_from_email',
5013 'receipt_from_name',
5014 'receipt_text',
5015 'custom_pre_id',
5016 'custom_post_id',
5017 'honoree_profile_id',
5018 'onbehalf_profile_id',
5019 'honor_block_is_active',
5020 // Kinda might be - but would be on the contribution...
5021 'campaign_id',
5022 'currency',
5023 // Included for 'fear of regression' but can't justify any use for these....
5024 'intro_text',
5025 'payment_processor',
5026 'financial_type_id',
5027 'amount_block_is_active',
5028 'bcc_receipt',
5029 'cc_receipt',
5030 'created_date',
5031 'created_id',
5032 'default_amount_id',
5033 'end_date',
5034 'footer_text',
5035 'goal_amount',
5036 'initial_amount_help_text',
5037 'initial_amount_label',
5038 'intro_text',
5039 'is_allow_other_amount',
5040 'is_billing_required',
5041 'is_confirm_enabled',
5042 'is_credit_card_only',
5043 'is_monetary',
5044 'is_partial_payment',
5045 'is_recur_installments',
5046 'is_recur_interval',
5047 'is_share',
5048 'max_amount',
5049 'min_amount',
5050 'min_initial_amount',
5051 'recur_frequency_unit',
5052 'start_date',
5053 'thankyou_footer',
5054 'thankyou_text',
5055 'thankyou_title',
5056
5057 );
5058 foreach ($valuesToCopy as $valueToCopy) {
5059 if (isset($contributionPageValues[$valueToCopy])) {
5060 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5061 }
5062 }
5063 return $values;
5064 }
5065
5066 /**
5067 * Get values of CiviContribute Settings
5068 * and check if its enabled or not.
5069 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5070 * in serialized form. Usually this should be stored as flat settings for each form fields
5071 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5072 * settings we will live with an inconsistency because it's too hard to change for now.
5073 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5074 *
5075 *
5076 * @param string $name
5077 * @return string
5078 *
5079 */
5080 public static function checkContributeSettings($name = NULL) {
5081 $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
5082
5083 if ($name) {
5084 return CRM_Utils_Array::value($name, $contributeSettings);
5085 }
5086 return $contributeSettings;
5087 }
5088
5089 /**
5090 * This function process contribution related objects.
5091 *
5092 * @param int $contributionId
5093 * @param int $statusId
5094 * @param int|null $previousStatusId
5095 *
5096 * @param string $receiveDate
5097 *
5098 * @return null|string
5099 */
5100 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5101 $statusMsg = NULL;
5102 if (!$contributionId || !$statusId) {
5103 return $statusMsg;
5104 }
5105
5106 $params = array(
5107 'contribution_id' => $contributionId,
5108 'contribution_status_id' => $statusId,
5109 'previous_contribution_status_id' => $previousStatusId,
5110 'receive_date' => $receiveDate,
5111 );
5112
5113 $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
5114
5115 if (!is_array($updateResult) ||
5116 !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) ||
5117 !is_array($updatedComponents) ||
5118 empty($updatedComponents)
5119 ) {
5120 return $statusMsg;
5121 }
5122
5123 // get the user display name.
5124 $sql = "
5125 SELECT display_name as displayName
5126 FROM civicrm_contact
5127 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5128 WHERE civicrm_contribution.id = {$contributionId}";
5129 $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
5130
5131 // get the status message for user.
5132 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5133
5134 if ($componentName == 'CiviMember') {
5135 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5136 CRM_Member_PseudoConstant::membershipStatus()
5137 );
5138 if ($updatedStatusName == 'Cancelled') {
5139 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5140 }
5141 elseif ($updatedStatusName == 'Expired') {
5142 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5143 }
5144 else {
5145 $endDate = CRM_Utils_Array::value('membership_end_date', $updateResult);
5146 if ($endDate) {
5147 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5148 array(
5149 1 => $userDisplayName,
5150 2 => $endDate,
5151 )
5152 );
5153 }
5154 }
5155 }
5156
5157 if ($componentName == 'CiviEvent') {
5158 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5159 CRM_Event_PseudoConstant::participantStatus()
5160 );
5161 if ($updatedStatusName == 'Cancelled') {
5162 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5163 }
5164 elseif ($updatedStatusName == 'Registered') {
5165 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5166 }
5167 }
5168
5169 if ($componentName == 'CiviPledge') {
5170 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5171 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
5172 );
5173 if ($updatedStatusName == 'Cancelled') {
5174 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5175 }
5176 elseif ($updatedStatusName == 'Failed') {
5177 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5178 }
5179 elseif ($updatedStatusName == 'Completed') {
5180 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5181 }
5182 }
5183 }
5184
5185 return $statusMsg;
5186 }
5187
5188 }