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